spring security动态配置权限的方案2

本文介绍一下spring security另外一种动态权限配置的方案

config

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public ExtAuthProvider extAuthProvider(){
        return new ExtAuthProvider();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login/**","/logout/**")
                .permitAll()
                .anyRequest().access("@authService.canAccess(request,authentication)");
    }

这里将所有的数据权限校验交给access这个方法定义的spring el表达式

authService

@Component
public class AuthService {

    public boolean canAccess(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if(principal == null){
            return false;
        }

        if(authentication instanceof AnonymousAuthenticationToken){
            //check if this uri can be access by anonymous
            //return
        }

        Set<String> roles = authentication.getAuthorities()
                .stream()
                .map(e -> e.getAuthority())
                .collect(Collectors.toSet());
        String uri = request.getRequestURI();
        //check this uri can be access by this role

        return true;

    }
}

这里可以单独把AnonymousAuthenticationToken拿出来校验,也可以将放到roles统一校验,其role为ROLE_ANONYMOUS

小结

使用这种方式,就没必要在每个方法上添加@PreAuthorize或者@Secured注解了,也就是不写死每个方法的权限,而是配置在数据库等其他存储,然后在AuthService里头运行时读取判断,这样就支持数据权限的动态修改和生效。

这种方法相比@PreAuthorize方式,有几点不足:

  • 需要自己从request中提取参数,而且这类参数需要相对通用,比如userId,orgId等
  • 对于使用PathVariable这种reset风格的参数提取相对比较费劲,而数据权限的校验往往又跟资源id是相关的

doc

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,771评论 19 139
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 13,894评论 6 13
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,107评论 6 342
  • 他还不错。 有正当职业,稳定而有发展,他做得很认真很努力。另外还有自己的事业,蓬勃而充满干劲,也很认真很努...
    嵩嵩穿着红舞鞋阅读 2,299评论 0 1
  • 近日,我都在准备下个月的英语等级考试。每当我在复习的过程中无法继续坚持下去的时候,我的脑子里就会闪过了杨绛老人对年...
    蓝色的寂寞阅读 3,677评论 0 1