Affects: Spring Boot V3.2.3 (Spring 6.1.4, Spring Security 6.2.2)


This is a similar situation as described in Stackoverflow: WebMvcTest with Spring Security seems to incorrectly return 404...

We came across this problem this week and were trying to isolate the root cause. In our project we have a RestController that is supposed to implement a generated OpenApi interface. The test fails to GET the resource from the controller's path, instead the default ResourceHttpRequestHandler is called and fails with status 404. The controller implementation is annotated with SpringSecurity @PreAuthorize. During debugging we found that the controller bean is not accessible from the application context (which we autowired into the test class and asked for the bean by classname).

See attached ZIP file of a SpringBoot sample project. It has one test class named ExampleApiControllerImplTest. This test will fail if you unzip and run the project. To make the test pass, comment out @PreAuthorize in the controller class ExampleApiControllerImpl.

spring-webmvc-testcase.zip

The solution given in the Stackoverflow answer mentioned above does not fix the problem for us - as as we assume - the controller is not added to the web application context in the first place. I cannot really identify if this is a problem within Spring, Spring Security, Spring WebMvc or Spring Boot and its many modules.

Please advise a workaround or any documentation for this problem.

Comment From: snicoll

This is due to the presence of the interface and annotations being used in mixed mode between the interface and the implementation. When Spring Security applies its advice it is configured by default to create a JDK proxy which hides the annotations on the implementation.

I've added @EnableMethodSecurity(proxyTargetClass = true) to your security config and the test passes.