When using WebFlux and Security with Spring Boot 2.3.4.RELEASE
In a test that gives @WebMvcTest
for testing a controller etc.
When I made a request to the controller with WebTestClient
, I was asked for Basic authentication for some reason.
It's a project that uses Spring Security, but it doesn't use Basic authentication.
Although the cause could not be investigated, there was an issue on GitHub.
In summary, @WebFluxTest
configures controller-related @Bean
s such as @Conroller
, @ControllerAdvice
, and WebFluxConfigurer
, but not @Bean
of @Service
.
However, it seems that the class with @Configuration
is generated as @Bean
.
And it seems that only @Bean
that matches the condition is generated from it.
If you have a security configuration for WebFlux of Spring Security, in most cases you will need to prepare the following configuration described in the document.
@Configuration
@EnableWebFluxSecurity
public class SecurityConfiguration {
@Bean
public SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
// do stuff
}
}
At this time, SecurityWebFilterChain
is not generated, but @EnableWebFluxSecurity
is scanned together with SecurityConfiguration
.
Looking at the definition of @EnableWebFluxSecurity
, [@Import (WebFluxSecurityConfiguration.class)](https://github.com/spring-projects/spring-security/blob/651c94b3859eb6c3eee4ee632b1419e59d99d8dd/config/src/main/java/org/springframework /security/config/annotation/web/reactive/EnableWebFluxSecurity.java#L87-L88) is added.
WebFluxSecurityConfiguration
will generate the default SecurityWebFilterChain (https://github.com/spring-projects/spring-security/blob/651c94b3859eb6c3eee4ee632b1419e59d99d8dd/config/src/main/java/org/springframework/security/config/annotation" /web/reactive/WebFluxSecurityConfiguration.java#L100-L111).
It seems that the default security of Spring Security is applied to the test with @WebFluxTest
in this way.
As a countermeasure, it seems that there is no choice but to explicitly @ Import`` @ Configuration
that generates SecurityWebFilterChain
prepared in the project.
Recommended Posts