Scheme 2 for spring security to dynamically configure permissions

  spring-security

Order

This article introduces another dynamic permission configuration scheme of 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)");
    }

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

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;

    }
}

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

Summary

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.

doc