spring security 方法安全@PreAuthorize实现从方法参数中获取数据并判断权限

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中判断权限

相关推荐
TracyCoder1233 天前
SpringSecurity 技术原理深度解析:认证、授权与 Filter 链机制
spring security
xiegwei10 天前
spring security oauth2 集成异常处理
数据库·spring·spring security
豆奶特浓615 天前
Java面试生死局:谢飞机遭遇在线教育场景,从JVM、Spring Security到AI Agent,他能飞吗?
java·jvm·微服务·ai·面试·spring security·分布式事务
努力发光的程序员16 天前
互联网大厂Java面试:从Spring Boot到微服务架构
spring boot·缓存·微服务·消息队列·rabbitmq·spring security·安全框架
陈果然DeepVersion1 个月前
Java大厂面试真题:Spring Boot+微服务+AI智能客服三轮技术拷问实录(四)
spring boot·redis·微服务·kafka·spring security·智能客服·java面试
喜欢读源码的小白1 个月前
【Spring Boot + Spring Security】从入门到源码精通:藏经阁权限设计与过滤器链深度解析
java·开发语言·spring boot·spring security
Hello World......1 个月前
互联网大厂Java面试实战:以Spring Boot与微服务为核心的技术场景剖析
java·spring boot·redis·微服务·junit·kafka·spring security
Jabes.yang2 个月前
Java面试大作战:从缓存技术到音视频场景的探讨
java·spring boot·redis·缓存·kafka·spring security·oauth2
Jabes.yang2 个月前
Java面试场景:从Spring Web到Kafka的音视频应用挑战
大数据·spring boot·kafka·spring security·java面试·spring webflux