I have this security configuration:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
// @formatter:off
@Override
public void configure(final HttpSecurity http) throws Exception {
http.headers().frameOptions().disable()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/test/**").authenticated()
.antMatchers("/**").permitAll()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
And this controller:
@RestController
public class MyController {
@GetMapping("")
@PreAuthorize("hasRole('ROLE_USER')")
public String hello() {
return "Hello world!";
}
@GetMapping("/api/test")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String helloTest(Principal principal) {
System.out.println(principal.toString());
return "Hello test world!";
}
}
Both controller methods have a @PreAuthorize annotation. In security configuration I require the /api/test/** endpoints to be secured, while the rest should be available as anonymous.
However when I test given controller, while opening http://localhost:8080 I get 401 Unauthorized because of the @PreAuthorize("hasRole('ROLE_USER')") annotation while I want it unsecured (.antMatchers("/**").permitAll()).
TL:DR - I want the "global" configuration overwrite the @PreAuthorize() annotation.
Why? Because I want to set the .antMatchers("/api/test/**").authenticated() part from the application.properties file so it can happen that if I change the value to "/api/test/hello/**" then I want the helloTest method be available for anonymous users without going through all the controllers and removing the @PreAuthorize() annotation everywhere and hope that I found it all. Thanks in advance.