Why is my SecurityWebFilterChain not being invoked?

I just started to learn Spring’s new reactive programming model and for this reason I tried to write a very basic webservice.

This is my application configuration:

@SpringBootApplication
@EnableWebFluxSecurity
public class ReactiveSpringApplication {

    public static void main(final String[] args) {
        SpringApplication.run(ReactiveSpringApplication.class, args);
    }

    @Bean
    public ReactiveUserDetailsService userDetailsService() {
        final UserDetails admin = User.withDefaultPasswordEncoder().username("admin").password("password").roles("ADMIN").build();
        final UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build();

        return new MapReactiveUserDetailsService(admin, user);
    }

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(final ServerHttpSecurity httpSecurity) {
        return httpSecurity
                .authorizeExchange()
                .anyExchange().authenticated().and()
                .httpBasic().and()
                .build();
    }

    @Bean
    public HttpHandler httpHandler() {
        final RouterFunction<ServerResponse> routes = route(GET("/"), serverRequest ->
                ServerResponse.ok().body(just("{"message":"Hello world!"}"), String.class));

        return RouterFunctions.toHttpHandler(routes);
    }

}

And this are my dependencies for now:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

When I make a GET request to http://localhost:8080/ I get a 200 OK response wit {"message":"Hello world!"} inside the body. However, I would expect a 401 Unauthorized response. The MatcherSecurityWebFilterChain that is built inside the securityWebFilterChain() method is not being invoked and thus no security rules are enforced.

What do I have to change in order to fix this issue?

Answer

By declaring your own HttpHandler, you are taking things into your own hands.

If you wish to leverage the Spring Boot + Spring Security support, you should instead declare RouterFunction beans and those will be mapped automatically.

See the Spring Framework reference documentation on that point.

Leave a Reply

Your email address will not be published. Required fields are marked *