首页 > 解决方案 > Spring 安全 webflux 中的 AuthenticationManger

问题描述

我正在尝试为我的 spring-webflux 应用程序构建一个自定义身份验证管理器。但是我发现我的经理从来没有被叫过。我的代码如下:

@Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
    return http
            .authorizeExchange().pathMatchers("/**").authenticated().and().httpBasic().disable()
            .securityContextRepository(webSessionServerSecurityContextRepository())
            .addFilterAfter(new AuthenticationWebFilter(bearerTokenAuthenticationManager()),
                    SecurityWebFiltersOrder.REACTOR_CONTEXT)
            .build();

}

我究竟做错了什么?

标签: spring-securityspring-webflux

解决方案


假设您将此 bean 放在一个带有注释的类中,@Configuration并且@EnableWebFluxSecurity您的问题似乎没有禁用csrfSpring Security 默认配置的。

您可以通过以下方式做到这一点:

@Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
    return http
            .authorizeExchange().pathMatchers("/**").authenticated()
            .and()
            .httpBasic().disable()
            .csrf().disable() // Disable csrf
            .securityContextRepository(webSessionServerSecurityContextRepository())
            .addFilterAfter(new AuthenticationWebFilter(bearerTokenAuthenticationManager()),
                    SecurityWebFiltersOrder.REACTOR_CONTEXT)
            .build();

}

此外,您必须正确配置AuthenticationWebFilter.

AnAuthenticationWebFilter具有以下依赖项:

AuthenticationWebFilter 依赖项

...它们中的大多数默认作为 HttpBasic deps 提供(从 Spring Security 源代码复制和粘贴):

private final ReactiveAuthenticationManagerResolver<ServerWebExchange> authenticationManagerResolver;

private ServerAuthenticationSuccessHandler authenticationSuccessHandler = new WebFilterChainServerAuthenticationSuccessHandler();

private ServerAuthenticationConverter authenticationConverter = new ServerHttpBasicAuthenticationConverter();

private ServerAuthenticationFailureHandler authenticationFailureHandler = new ServerAuthenticationEntryPointFailureHandler(new HttpBasicServerAuthenticationEntryPoint());

private ServerSecurityContextRepository securityContextRepository = NoOpServerSecurityContextRepository.getInstance(); // Stateless session

private ServerWebExchangeMatcher requiresAuthenticationMatcher = ServerWebExchangeMatchers.anyExchange();

你可以使用 setters 方法设置任何你想要的东西AuthenticationWebFilter。AnAuthenticationWebFilter具有以下逻辑:

AuthenticationWebFilter 流

因此,根据具体情况,您必须配置一个或另一个依赖项。您可以在我的仓库中看到身份验证和授权如何工作的完整示例:https ://github.com/soasada/kotlin-coroutines-webflux-security (在 kotlin 中,但情况相同)


推荐阅读