环境
JDK 17
- Spring Boot 3.2.1-3.3.2
- Spring Security 6.2.1-6.3.1
Spring Security 权限/角色常用注解
@Secured
:方法执行前检查,直接判断有没有对应的角色@PreAuthorize
:方法执行前检查,根据SpEL表达式执行结果判断是否授权@PostAuthorize
:方法执行后检查,根据SpEL表达式执行结果判断是否授权
要使用以前注解必须增加配置,开启方法安全校验功能
配置参考1
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
配置参考2
@EnableMethodSecurity(securedEnabled = true, prePostEnabled = true)
配置方法一直在变化一个弃用一个没弃用,自行选择。
@Secured
方法执行前检查,直接判断有没有对应的角色
代码聚焦
@Secured({ "ROLE_USER" })
public void create(Contact contact);
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public void update(Contact contact);
@Secured({ "ROLE_ADMIN" })
public void delete(Contact contact);
解说:
- 第一个判断必须要有
ROLE_USER
角色才能操作; - 第二个判断需要有
ROLE_USE+ROLE_ADMIN
才能操作 - 第三个判断需要有
ROLE_ADMIN
角色才能操作
@PreAuthorize
方法执行前检查,根据SpEL表达式执行结果判断是否授权
代码聚焦
// 有角色ROLE_ADMIN
@PreAuthorize("hasRole('ROLE_ADMIN')")
// 有括号里面包含的任一角色
@PreAuthorize("hasAnyRole({'ROLE_USER','ROLE_ADMIN'})")
// 有括号里面包含的任一权限
@PreAuthorize("hasAnyAuthority({'user:search','user:edit'})")
PreAuthorize
参数是SpEL表达式,所以还可以有其他用法
1、方法参数值判断,@PreAuthorize("#age>10")
@GetMapping("/age")
@PreAuthorize("#age>10")
public String age(Integer age) {
return "Hello age "+ age;
}
2、调用bean的方法判断
1)创建Bean,判断是否有权限
@Component("au")
public class AuthUtils {
public boolean check(String role) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.noneMatch(role::equals)) {
throw new AccessDeniedException("User does not have the required permission");
}
return true;
}
}
2)在方法上使用,@PreAuthorize("@au.check('ROLE_USER')")
@GetMapping("/user_au")
@PreAuthorize("@au.check('ROLE_USER')")
public String user_au() {
return "Hello user_au";
}
和@PreAuthorize
配合使用的方法定义在 org.springframework.security.access.expression.SecurityExpressionOperations
中

https://www.syntaxspace.com/article/2408191355278391.html
评论