为什么我的 SecurityWebFilterChain 没有被调用?

Why is my SecurityWebFilterChain not being invoked?

我刚开始学习 Spring 的新反应式编程模型,因此我尝试编写一个非常基本的网络服务。

这是我的应用程序配置:

@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);
    }

}

这是我现在的依赖项:

<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>

当我向 http://localhost:8080/ 发出 GET 请求时,我在正文中收到 200 OK 响应 {"message":"Hello world!"}。但是,我希望得到 401 Unauthorized 响应。 securityWebFilterChain() 方法中内置的 MatcherSecurityWebFilterChain 未被调用,因此未强制执行任何安全规则。

我需要更改什么才能解决此问题?

通过声明你自己的 HttpHandler,你正在把事情掌握在自己手中。

如果您希望利用 Spring 引导 + Spring 安全支持,您应该改为声明 RouterFunction bean,这些 bean 将被自动映射。

参见Spring Framework reference documentation on that point