本文介紹一下spring security另一種動態權限配置的方案spring
@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表達式數據庫
@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