'Configure Spring HTTP Security at Runtime

All http security is applied at startup:

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/admin/**").hasRole("admin")
}

During runtime, I am trying to add more to it ...

applicationContext.getBean(WebSecurityConfigurerAdapter).http.authorizeRequests().antMatchers("bla").hasRole("admin")

When that line is executed, it adds it to http.authorizeRequests()'s but /bla is still accessible by "non admins"

When server is restarted, this change takes effect because it is loading bla from the database.

How do I make the security take effect instantly without restarting the server?



Solution 1:[1]

You are trying to dynamicaly change a spring bean at runtime which is very hard to do unless you use tools like spring-loaded or JRebel. There is a lot of SO about it :

  1. Update spring beans dynamically. Is it possible?
  2. dynamically change spring beans
  3. Can I replace a Spring bean definition at runtime?

The best approach (in my opinion) for your use case is to use spring profiles.
Define a bean with authorisations for /bla and another bean without. Then use them in different profiles.

see dynamically declare beans at runtime in Spring

Solution 2:[2]

My solution to these case scenarios is to make a dynamic custom spring security rule to match with all the path.

    http
        .authorizeRequests()
        .antMatchers("/**").access("@customSecurityRule.check(authentication)");

This way new endpoint will automatically be configured with our custom security rule, and in our custom security rule we can preety much do anything we want, checking their roles, validate it againts our database and etc.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Aleson