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

Spring Boot 3.0+Security 6+WebFlux在Postman中遇CSRF令牌缺失问题求助

Spring Boot 3.0.0中SecurityWebFilterChain CSRF失效问题解决方法

你的配置在Spring Boot 2.7.x正常运行,但升级到3.0.0后调用REST API时提示**“找不到预期的CSRF令牌”**,问题出在配置的嵌套写法上——Spring Security 6.0(Spring Boot 3.0依赖版本)对WebFlux安全配置的结构做了调整,导致原有嵌套的CSRF禁用配置未生效。

问题原因

在authorizeExchange的lambda配置内部,你通过.and().cors().disable().csrf().disable()尝试再次禁用CSRF,但这种嵌套写法在Spring Security 6.0的WebFlux配置中不再有效:authorizeExchange的配置块应该仅用于定义路径授权规则,内部的and()无法正确切换到其他安全配置项,导致这部分CSRF禁用逻辑被忽略,最终CSRF防护依然处于开启状态。

修正后的配置代码

移除authorizeExchange内部的无效嵌套配置,确保CSRF禁用在顶层配置中生效:

@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
    http
            .cors().disable()               
            .csrf().disable()
            .exceptionHandling()
                .authenticationEntryPoint((swe, e) -> 
                    Mono.fromRunnable(() -> swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED))
                )
                .accessDeniedHandler((swe, e) -> 
                    Mono.fromRunnable(() -> swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN))
                )
                .and()
            .authenticationManager(authenticationManager)
            .securityContextRepository(securityContextRepository)
            .authorizeExchange(exchange -> exchange                                      
                    .pathMatchers(HttpMethod.OPTIONS).permitAll()
                    .pathMatchers("/login", "/register").permitAll()                        
                    .anyExchange().authenticated()
            )
            .formLogin().disable()
            .httpBasic().disable();
            
    return http.build();
}

关键调整说明

  1. 删掉authorizeExchange内部的.and().cors().disable().csrf().disable(),这部分属于错误的嵌套配置,完全冗余且会导致配置失效。
  2. 顶层已经配置了.csrf().disable(),最终build()前无需重复调用csrf(csrf -> csrf.disable()),保持配置链式调用的简洁性即可。

内容的提问来源于stack exchange,提问作者EricMacau

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:55:10