我想在Spring Gateway应用程序中处理csrf,但在飞行前请求或后续GET请求的响应标头中都没有看到生成的csrf令牌。我读了一遍,发现我需要使用WebFluxSecurity来保护应用程序。
这是我的Webflux安全配置:
@Configuration
@EnableWebFluxSecurity
public class SpringSecurityConfig {
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange().pathMatchers("/helloworld/*").permitAll()
.and().csrf(csrf -> csrf.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()))
.httpBasic().disable();
;
return http.build();
}
}
非常感谢您的帮助!
这将导致生成令牌并自动添加
@Component
class AddCsrfHeaderFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
Mono<CsrfToken> tokenMono = (Mono<CsrfToken>) exchange.getAttributes().get(CsrfToken.class.getName());
if (tokenMono != null) {
return tokenMono.flatMap(token -> chain.filter(exchange)); // When the application subscribes to this
// producer, it causes the token to be generated, and it is automatically added to the response
}
return chain.filter(exchange);
}
}