spring security版本:6.4.12
注解中使用hasRole方法,不能从方法参数中获取角色key,需要实现PermissionEvaluator接口。
实现PermissionEvaluator
java
/**
* spring security自定义权限检查(hasPermission)
* 检查token中是否有request中请求对象的权限
*
* 如@PreAuthorize("hasPermission(#c, 'write')")
* #c对应参数targetDomainObject
* 不需要传第一个参数authentication
*
* @author xgw
* @since 2024-15-10
*/
@Slf4j
public class MyPermissionEvaluator implements PermissionEvaluator {
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
log.debug("判断权限:{}", permission);
//todo 检查authentication中是否有targetDomainObject(参数)的权限
//暂时全通过
return true;
}
@Override
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
return false;
}
}
配置自定义的PermissionEvaluator到springSecurity中
java
@Bean
static MethodSecurityExpressionHandler expressionHandler() {
PermissionEvaluator permissionEvaluator = new MyPermissionEvaluator();
final DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(permissionEvaluator);
return expressionHandler;
}
在controller中使用
java
@PreAuthorize("hasPermission(#vo, 'write')")
@DeleteMapping("v2/role/user")
public void deleteRole(
@P("vo")@Valid @RequestBody DeleteRoleVO vo) {
roleService.deleteRole(vo);
}
vo会被传到MyPermissionEvaluator中判断权限