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

相关推荐
Cry丶12 天前
架构师实战:Spring Authorization Server 落地企业级“无感” SSO(附设计映射与源码级接口剖析)
spring·spring security·oauth2.0·authorization·sso·无感登录
Devin~Y12 天前
大厂Java面试实录:Spring Boot/Cloud + Redis/Kafka + JWT + RAG/Agent(小Y翻车版)
java·spring boot·redis·spring cloud·kafka·spring security·jwt
Devin~Y19 天前
大厂 Java 面试实战:Spring Boot 微服务 + Redis 缓存 + Kafka 消息 + Kubernetes + RAG(小Y水货翻车记)
java·spring boot·redis·kafka·spring security·jwt·oauth2
indexsunny20 天前
互联网大厂Java面试实录:微服务+Spring Boot在电商场景中的应用
java·spring boot·redis·微服务·eureka·kafka·spring security
indexsunny22 天前
互联网大厂Java面试实战:核心技术与微服务架构在电商场景中的应用
java·spring boot·redis·kafka·maven·spring security·microservices
Devin~Y22 天前
从Spring Boot到Spring AI:音视频AIGC内容社区Java大厂面试三轮连环问(含Kafka/Redis/安全/可观测性答案)
java·spring boot·redis·spring cloud·kafka·spring security·resilience4j
indexsunny25 天前
互联网大厂Java求职面试实战:Spring Boot与微服务架构解析
java·spring boot·redis·kafka·spring security·flyway·microservices
indexsunny1 个月前
互联网大厂Java面试实战:从Spring Boot到微服务架构的技术问答
java·spring boot·redis·微服务·面试·kafka·spring security
星轨zb2 个月前
通过实际demo掌握SpringSecurity+MP中的基本框架搭建
数据库·spring boot·spring security·mp