8

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?

2 Answers2

0

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

Community
  • 1
  • 1
Issam El-atif
  • 2,366
  • 2
  • 17
  • 22
  • 1
    The problem here is that he is modifying the configuration bean. I think modifying the securityfilterchain at runtime would be an option if the underlying chain is accessible. But it's true that alot of spring beans are not meant for that and you need to wrap such beans with delegates so you can rebuild the singletons if needed. – Martin Frey Nov 07 '16 at 17:06
  • 1
    Its 100% dynamic, profiles + classes per profile wouldn't work as there is no way to know the possibilities. The http.authorizeRequests().urlMappings is getting the new item during runtime, but spring is not see'ing it when the URL is hit. – Matthew Struensee Nov 07 '16 at 18:41
0

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.

Aleson
  • 332
  • 2
  • 9