Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权。
一般来说,
Web
应用的安全性包括用户认证(
Authentication
)和用
户授权(
Authorization)两个部分。
①用户认证指的是验证某个用户是否为系统中的合法主体,也就是说 用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。
在用户认证方面,
Spring Security 框架支持主流的认证方式,包括
HTTP
基本认证、
HTTP
表单验证、
HTTP
摘要认证、
OpenID 和 LDAP
等。
②用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权 限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系
统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。
在用户授权方面,
Spring Security
提供了基于角色的访问控制和访问控制列表(
Access Control List,
ACL
),可以对应用中的领域对象进行细粒度的控制。
![](https://img-blog.csdnimg.cn/6803b2d652b94100b0bfe6d42bb9c85f.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6IGq5piO5Ly25L-Q5p2o5qGD5a2Q,size_13,color_FFFFFF,t_70,g_se,x_16)
1.引入模块
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.框架
@EnableWebSecurity // 开启WebSecurity模式
public class securityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception{
super.configure(http);
}
}
3.进入父类中可以查看方法
4.从内存中授权,登录(也可从数据库授权,暂略)
授权:
//授权
@EnableWebSecurity // 开启WebSecurity模式
public class securityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception{
// 首页所有人可以访问
// 定制请求的授权规则
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
// /login 请求来到登录页
//没有权限会默认到登陆页面 /Login
http.formLogin();
}
认证:
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//可以从数据库或内存里认证
//Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
// 要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
// spring security 官方推荐的是使用bcrypt加密方式
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("taozi").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1","vip2","vip3");
}
5.权限控制和注销
P36