spring-security - 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();
}
我究竟做错了什么?
解决方案
假设您将此 bean 放在一个带有注释的类中,@Configuration
并且@EnableWebFluxSecurity
您的问题似乎没有禁用csrf
Spring 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
具有以下依赖项:
...它们中的大多数默认作为 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
具有以下逻辑:
因此,根据具体情况,您必须配置一个或另一个依赖项。您可以在我的仓库中看到身份验证和授权如何工作的完整示例:https ://github.com/soasada/kotlin-coroutines-webflux-security (在 kotlin 中,但情况相同)
推荐阅读
- php - 如何更改 PHP 内置服务器上的文件扩展名处理?
- javascript - 从 php->mysql 中的 xml 深度节点
- android - 崩溃仅在 Android 8 中发生
- javascript - VS Code extension code unable to find JSON path
- oracle-apex - Oracle Apex 5.1.4 中的语言验证
- node.js - NetBeans 上的 WebApp 项目显示:“Node.js:缺少 node.js 源(在 NodeJsWebApplication 中)”
- python - Python没有从列表中删除元素
- telegram - Telegram user_id 的长度可以是多少?
- angular - iframe 在 Angular 5 中不起作用,它显示的是 html 内容
- f# - 功能组合错误