Scheme 2 for spring security to dynamically configure permissions



This article introduces another dynamic permission configuration scheme of spring security.


public class SecurityConfig extends WebSecurityConfigurerAdapter {

    public ExtAuthProvider extAuthProvider(){
        return new ExtAuthProvider();

    protected void configure(HttpSecurity http) throws Exception {

Here, all data permission checks are given to the spring el expression defined by the access method.


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

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

        return true;


Here, AnonymousAuthenticationToken can be taken out separately for verification, or it can be put into roles for unified verification, and its role is ROLE_ANONYMOUS


In this way, it is not necessary to add @PreAuthorize or @Secured annotation to each method, that is, instead of writing down the permissions of each method, it is configured in other storage such as databases and then read the judgment when running in AuthService, thus supporting dynamic modification and validation of data permissions.

Compared with @PreAuthorize, this method has several disadvantages:

  • You need to extract parameters from the request yourself, and these parameters need to be relatively common, such as userId, orgId, etc.
  • It is relatively difficult to extract parameters using the reset style of PathVariable, and the verification of data permissions is often related to the resource id.