Spring Security @PreAuthorize on controllers

I am trying to use url (ant) matching with @PreAuthorize ("allowAll") on some ie controllers

@Controller @RequestMapping("/register") public class RegistrationController { ... @PreAuthorize("permitAll") @RequestMapping(method = RequestMethod.GET) public String register() { ... } 

SecurityConfig:

 @Configuration @EnableWebMvcSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http .authorizeRequests() .antMatchers("/").permitAll() .anyRequest().authenticated() 

I also tried adding @EnableGlobalMethodSecurity to my MVC configuration:

 @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class MvcConfig extends WebMvcConfigurerAdapter { ... } 

But it has no effect

However, I am still invited to authenticate when clicked / registered. If I add "/ register" to ant matches, it works, that is .antMatchers ("/", "/ register"). AllowAll ()

What am I missing here? It seems that @PreAuthorize does not affect my controllers.

+6
source share
1 answer

You cannot do this because ant and @PreAuthorize work at different levels.

Ant connectors work at http security level. Spring Security Filter scans the request, and if it detects that access should be denied, it does not even send the request to the dispatcher server and directly sends a 403 error.

PreAuthorize work at the method level. When the method is called, the AOP proxy controls whether access should be allowed. Thus, authorization level 2 is attached , and the second is the first.

In any case, I highly recommend that you not use @PreAuthorize("hasRole('ADMIN')") on the controller:

  • it can be easily done with a simple ant match
  • it forces you to enable proxying on the controller, either with a proxy server instead of proxying the JDK, or using the interfaces for the controllers.

IMHO, @PreAuthorize best suited for the service level, as you can mix domain objects with user privileges to get fine-grained permissions.

+8
source

Source: https://habr.com/ru/post/988161/


All Articles