I am using @PreAuthorize
on methods in service interfaces. Theses services are used by @RestController
classes
With Spring Boot 2.x I enabled method security in a AutoConfiguration with @EnableGlobalMethodSecurity(prePostEnabled = true)
In some @SpringBootTest
s we concentrate on testing the functional logic and don’t care about method security. Theses tests do no call a rest service or controller class. They directly call method from above mentioned service classes which are annotated with @PreAuthorize
. In these tests we disabled the method security by
@EnableAspectJAutoProxy
class MyTestApplication extends MySringBootApplication {
@Bean
public GeFaJwtInterceptorTestAspect jwtInterceptorTestAspect() {
return new GeFaJwtInterceptorTestAspect();
}
@Bean
@Primary
SecurityMetadataSource disableMethodSecurityForUnitTest() {
return new DefaultFilterInvocationSecurityMetadataSource(Maps.newLinkedHashMap());
}
}
That works fine.
After migration to Spring Boot 3 I am using @EnableMethodSecurity
now.
How can I disable Spring’s security method in unit tests?
I read the article https://docs.spring.io/spring-security/reference/servlet/authorization/method-security.html#enable-annotation but did not find a solution there.
I tried out
- using
@EnableMethodSecurity(prePostEnabled = false)
atMyTestApplication
- adding a bean in my test configuration
@Primary @Order(Ordered.HIGHEST_PRECEDENCE) AuthorizationManager<MethodInvocation> disableMethodSecurityForUnitTest1() { return (authentication, object) -> new AuthorizationDecision(true); }
But that did not work. Each try end up in the following exception
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
Currently my only fix is to add @WithMockUser
on each test method which is not want I want as I want to test the functional logic only. (Method security is tested, too, but on another layer in our application.)