I have a Spring Boot app that provides REST APIs. All the API are secured with Spring Security. I also have added method authorization using @PreAuthorize annotation.
For local development I would like to disable security altogether via a configuration or something. I want to disable both authentication and authorization so that I can easily call the APIs without having to acquire a fresh token each time I want to call the API.
Disabling Authentication is easy, I just added this to a config method and all good.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/api/**");
}
But this causes AuthenticationCredentialsNotFoundException when hitting the endpoints that I excluded from authentication which makes sense. This exception goes away only when I remove the @PreAuthorize annotation which obviously I don't want to do whenever I'm about to do some local development work. It seems just by having the annotation on methods, Spring AOP kicks and checks for authentication object in Spring Security Context and there's no way to disable it rather than removing the annotations.
How can I get Spring to ignore @PreAuthorize annotations altogether? I tried removing @EnableGlobalMethodSecurity but it didn't help with the exception.
enabled=false and management. security. enabled=false should be set to disable the security.
Method-level security is implemented by placing the @PreAuthorize annotation on controller methods (actually one of a set of annotations available, but the most commonly used). This annotation contains a Spring Expression Language (SpEL) snippet that is assessed to determine if the request should be authenticated.
I met the same problem, and I solved it with below code:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${security.enabled:true}")
private boolean securityEnabled;
@Override
public void configure(WebSecurity web) throws Exception {
if (!securityEnabled) {
web.ignoring().antMatchers("/**");
}
}
/**
* ommit codes
*/
/**
* control @EnableGlobalMethodSecurity(prePostEnabled = true),to solve AuthenticationCredentialsNotFoundException
*/
@ConditionalOnProperty(prefix = "security",
name = "enabled",
havingValue = "true")
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class Dummy {
}
}
if security.enabled=false
, Dummy
bean will not be created, therefore @EnableGlobalMethodSecurity(prePostEnabled = true)
will also does not exist, and finally @PreAuthorize
annotation will be ignored.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With