SpringSecurity注解
需求缘起
在之前的章节中我们介绍过通过注解的⽅式进⾏权限的控制了,这⾥再详细的讲解下⽅法级安全的⼏个注解。
⼀、注解式⽅法级安全开启
需要在WebSecuirtyConfig添加配置:
@Configuration
@EnableWebSecurity //启⽤Spring Security.
////会拦截注解了@PreAuthrize注解的配置.
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
}
⼆、允许的注解
这⾥主要@PreAuthorize, @PostAuthorize, @Secured这三个注解可以使⽤。
2.1 @Secured
当@EnableGlobalMethodSecurity(securedEnabled=true)的时候,@Secured可以使⽤:
@GetMapping("/helloUser")
@Secured({"ROLE_normal","ROLE_admin"})
public String helloUser() {
return "hello,user";
}
说明:拥有normal或者admin⾓⾊的⽤户都可以⽅法helloUser()⽅法。另外需要注意的是这⾥匹配的字符串需要添加前缀“ROLE_“。
如果我们要求,只有同时拥有admin & noremal的⽤户才能⽅法helloUser()⽅法,这时候@Secured就⽆能为⼒了。
2.2 @PreAuthorize
Spring的 @PreAuthorize/@PostAuthorize 注解更适合⽅法级的安全,也⽀持Spring 表达式语⾔,提供了基于表达式的访问控制。
当@EnableGlobalMethodSecurity(prePostEnabled=true)的时候,@PreAuthorize可以使⽤:
@GetMapping("/helloUser")
@PreAuthorize("hasAnyRole('normal','admin')")
public String helloUser() {
return "hello,user";
}
说明:拥有normal或者admin⾓⾊的⽤户都可以⽅法helloUser()⽅法。
此时如果我们要求⽤户必须同时拥有normal和admin的话,那么可以这么编码:
@GetMapping("/helloUser")
@PreAuthorize("hasRole('normal') AND hasRole('admin')")
public String helloUser() {
return "hello,user";
hellospring是什么意思}
此时如果使⽤user/123登录的话,就⽆法访问helloUser()的⽅法了。
2.3 @PostAuthorize
@PostAuthorize 注解使⽤并不多,在⽅法执⾏后再进⾏权限验证,适合验证带有返回值的权限,Spring EL 提供返回对象能够在表达式语⾔中获取返回的对象returnObject。
当@EnableGlobalMethodSecurity(prePostEnabled=true)的时候,@PostAuthorize可以使⽤:
@GetMapping("/helloUser")
@PostAuthorize(" returnObject!=null &&  returnObject.username == authentication.name")
public User helloUser() {
Object pricipal = Context().getAuthentication().getPrincipal();
User user;
if("anonymousUser".equals(pricipal)) {
user = null;
}else {
user = (User) pricipal;
}
return user;
}
这三个最常⽤也就是@PreAuthorize这个注解了,在使⽤中主要是配合Spring EL表达式。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。