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

相關文章
相關標籤/搜索