一、概念
两个操作:
1、认证(Authentication):确认用户可否访问当前系统
2、授权(Authorization):确认用户在当前系统中拥有的功能权限
二、例子
1.pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.SecurityConfig配置类
继承WebSecurityConfigurerAdapter
public class SecurityConfig extends WebSecurityConfigurerAdapter{
//连接Redis数据库
@Autowired
StringRedisTemplate stringRedisTemplate;
@Resource(name = "stringRedisTemplate")
ValueOperations<String,String>valueOperations;
}
3.用户认证
重写configure方法
AuthenticationManagerBuilder创建用户及其对应角色
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
//user用户的用户角色为“USER”
auth.inMemoryAuthentication().withUser(valueOperations.get("user")).password(passwordEncode().encode(valueOperations.get("user_password"))).roles("USER");
//dbm用户的用户角色为“DBM”
auth.inMemoryAuthentication().withUser(valueOperations.get("dbm")).password(passwordEncode().encode(valueOperations.get("dbm_password"))).roles("DBM");
//admin用户的用户角色为“ADMIN”
auth.inMemoryAuthentication().withUser(valueOperations.get("admin")).password(passwordEncode().encode(valueOperations.get("admin_password"))).roles("ADMIN");
}
4.用户授权
利用HttpSecurity的authorizeRequests()方法处理URL访问策略
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
httpSecurity.authorizeRequests()
//所有用户均可访问该地址
.antMatchers("/alllogin").permitAll()
//只有是“ADMIN”的用户角色才可访问该地址
.antMatchers("/adminlogin").hasRole("ADMIN")
//其余所有请求均需验证
.anyRequest().authenticated()
.and()
.logout()
.permitAll()
.and()
.formLogin();
}
5.控制类
@RestController
public class LoginController {
@RequestMapping("/alllogin")
public String all() {
return "hello world no security";
}
//设置访问该地址的用户权限,只有用户角色为“DBM”才能访问该地址
@PreAuthorize("hasRole('ROLE_DBM')")
@RequestMapping("/dbmlogin")
public String dbm(Authentication authentication) {
return "hello world must DBM security" + authentication.getName();
}
@RequestMapping("/adminlogin")
public String admin(Authentication authentication){
return "hello world must security"+authentication.getName();
}
}
6.结果
结果 | 输入 | 地址栏 | ||
/alllogin | /dbmlogin | /adminlogin | ||
Username和Password | user | √ | error | error |
dbm | √ | √ | error | |
admin | √ | error | √ |