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

Spring Cloud Gateway报“An expected CSRF token cannot be found”问题咨询

问题原因分析

这个问题核心是Spring Boot 3.x(对应Spring Security 6.x、Spring Cloud Gateway 4.x)版本升级后,CSRF保护的默认逻辑和配置优先级发生了变更,具体原因如下:

  • Security配置逻辑的版本差异:
    Spring Boot 2.7.x使用的Spring Security 5.7.x中,csrf().disable()可以直接全局关闭CSRF校验;但升级到Spring Security 6.x后,WebFlux环境下的CSRF过滤器优先级、默认生效范围都有调整,若自定义配置的加载顺序滞后于自动配置的Security规则,会导致disable()不生效,依然触发CSRF校验。

  • Gateway与Security的过滤器顺序冲突:
    新版本Spring Cloud Gateway的路由过滤器与Spring Security的CSRF过滤器执行顺序发生了变化,请求可能在到达自定义Security配置的过滤器之前,就被默认启用的CSRF过滤器拦截,从而抛出token缺失的错误。

  • 配置类的生效优先级问题:
    若项目中存在其他Security相关配置类,或者自动生成的SecurityWebFilterChain Bean优先级高于自定义配置,会导致你写的csrf.disable()规则不被应用。

验证与解决建议

  1. 显式添加@Configuration注解:
    虽然@EnableWebFluxSecurity本身包含配置类注解,但显式添加可以避免版本兼容问题,确保配置类被正确识别:

    @Configuration
    @EnableWebFluxSecurity
    public class SpringSecurityConfig {
    
        @Bean
        public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
            http
                    .csrf(csrf -> csrf.disable())
                    .authorizeExchange(authorize -> authorize
                            .requestMatchers(HttpMethod.POST, "/**").permitAll()
                            .anyExchange().permitAll()
                    );
            return http.build();
        }
    }
    
  2. 提升自定义配置的优先级:
    给自定义的SecurityWebFilterChain Bean添加最高优先级注解,确保它先于自动配置的规则生效:

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        // 原有配置逻辑
    }
    
  3. 检查项目中是否存在其他Security配置:
    排查是否有其他SecurityWebFilterChain Bean或者Security相关自动配置类,避免规则冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:43:25