You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Web Flux Basic Authentication响应式场景下对指定URL禁用CSRF

Spring WebFlux 特定URL禁用CSRF配置方案

核心实现思路是无需全局关闭CSRF校验,直接通过CSRF配置的路径忽略规则指定要排除的URL即可,调整后的配置如下:

推荐写法(Spring Security 5.2+ Lambda风格)

@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
    return http
            .csrf(csrf -> csrf
                // 按实际需求填写需要禁用CSRF的路径,支持通配符
                .ignoringMatchers(
                    new PathPatternParserServerWebExchangeMatcher("/api/no-csrf/**"),
                    new PathPatternParserServerWebExchangeMatcher("/third-party/webhook")
                )
            )
            .authorizeExchange(exchange -> exchange
                .anyExchange().authenticated()
            )
            .httpBasic(Customizer.withDefaults())
            .build();
}

兼容低版本写法

适用于不支持Lambda配置的低版本Spring Security

@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
    return http
            .csrf()
                // 配置忽略CSRF校验的路径
                .ignoringMatchers(
                    new PathPatternParserServerWebExchangeMatcher("/api/no-csrf/**"),
                    new PathPatternParserServerWebExchangeMatcher("/third-party/webhook")
                )
            .and()
            .authorizeExchange()
                .anyExchange().authenticated()
            .and()
            .httpBasic()
            .and()
            .build();
}

扩展说明

  • 路径匹配支持标准Spring路径通配符:*匹配单层路径,**匹配多层任意路径
  • 如需更复杂的匹配规则(比如仅排除指定请求方法的路径),可自定义ServerWebExchangeMatcher实现,示例如下:
// 仅排除POST方法的/pay/callback路径
.csrf(csrf -> csrf
    .ignoringMatchers(exchange -> Mono.just(
        exchange.getRequest().getMethod() == HttpMethod.POST
        && new PathPatternParser()
            .parse("/pay/callback")
            .matches(exchange.getRequest().getPath().pathWithinApplication())
    ))
)

内容的提问来源于stack exchange,提问作者Dhananjaya Samanta Singhar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:24:05