Home > Net >  Spring Security add/remove antMatchers and roles dynamically at runtime
Spring Security add/remove antMatchers and roles dynamically at runtime

Time:10-05

Is there a way to change this place dynamically? In other words, invoke the method that adds or removes antMatchers or override completely. map roles, etc.

@EnableWebSecurity
public class WebSecurityConfigAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //Change this configs dynamically at runtime
    }
    
}

CodePudding user response:

I ended up with this solution. The solution is to close the current context and run the new one. Of course, it has the disadvantage because it causes downtime but I use a load balancer and several nodes so it's was ok for me.

CodePudding user response:

In Spring Security version 5.6, which is in 5.6.0.M3 as of now, you can create an AuthorizationManager bean and define place your rules anywhere you want, like so:

@Autowired
private MyCustomAuthorizationManager access;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().access(access);
}

Or even better, you can define a SecurityFilterChain bean and make use of method parameter injection, instead of extending WebSecurityConfigurerAdapter:

@Bean
SecurityFilterChain app(HttpSecurity http, MyCustomAuthorizationManager access) throws Exception {
     ...
     http.authorizeRequests().access(access);
     ...
     return http.build();
}

There is a great presentation showing how to do this.

  • Related