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

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

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_ANONYMOUSsegmentfault

小结

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

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

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

doc

相关文章
相关标签/搜索