I am not too sure exactly where is the issue yet. But With a conf.
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(final HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authorize -> authorize
.anyRequest().permitAll())
.httpBasic(withDefaults())
.exceptionHandling(withDefaults());
return http.build();
}
}
And
controller like :
@RestController
public class HelloController implements HelloControllerInterface {
public String get(String id) {
System.out.println(id);
return id;
}
}
public interface HelloControllerInterface {
@PreAuthorize("hasRole('ROLE_AUTHENTICATED')")
@GetMapping("/test")
public String get(@RequestParam String id);
}
Test are not working :
@Import(SecurityConfig.class)
@WebMvcTest(value = HelloController.class)
class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void failingTest() throws Exception {
mockMvc.perform(get("/test?id=sss")).andExpect(status().isOk()).andReturn().getResponse();
assertTrue(true);
}
}
The call return a 404. But should not. That works perfectly if you don't use @EnableMethodSecurity or if your don't use the interface to define the annotation.
That is with Spring boot 3.2.5.
Comment From: wilkinsona
Thanks for the report, but it's not clear to me why you have opened a Spring Boot issue. Spring Boot isn't involved with the discovery of the @PreAuthorize annotations. It's Spring Security that does that. Perhaps you're saying that the problem only occurs with @WebMvcTest and doesn't occur when running the application's main method or perhaps when using @SpringBootTest? If that's the case and you would like us to investigate, please provide a complete yet minimal sample that demonstrates these differences in behaviour. If that's not the case, this should probably be a Spring Security issue as it sounds like it's out of Spring Boot's control.
Comment From: alexisgayte
Yes that is the case it is linked to @WebMvcTest I believe. Everything works fine otherwise, the app itself is fine.
Here is the test repo : https://github.com/alexisgayte/spring-framework-30489/tree/main
I personally moved the interface into the controller that resolved my issue. But that looks a bug. May be Spring Security but looks more on @WebMvcTest.
The test fail due to a 404. meaning spring can't find the mapping.
Comment From: wilkinsona
Thanks for the sample. It allowed me to determine that this is a duplicate of https://github.com/spring-projects/spring-boot/issues/33415. You can work around it by importing AOP auto-configuration:
@Import(SecurityConfig.class)
@WebMvcTest(value = HelloController.class)
@ImportAutoConfiguration(AopAutoConfiguration.class)
class HelloControllerTest {
Comment From: alexisgayte
Thanks for your time.