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

Spring Boot 3.0.1中CsrfFilter校验异常问题求助

问题根源

Spring Boot 3.0.1(对应Spring Security 6)默认使用32字节随机数Base64编码的CSRF Token,而你的前端请求头传递的是UUID格式字符串。XorCsrfTokenRequestAttributeHandler会对请求头的Token做Base64解码,UUID字符串解码后得到的字节数组长度不足32,导致校验失败。


解决方案

方案1:适配UUID格式的Token(兼容当前Cookie)

修改Spring Security配置,指定使用UUID生成Token,并替换掉默认的异或校验处理器:

@Bean
public CsrfTokenRepository tokenRepository() {
    CookieCsrfTokenRepository tokenRepo = CookieCsrfTokenRepository.withHttpOnlyFalse();
    tokenRepo.setCookiePath("/");
    // 强制使用UUID生成器
    tokenRepo.setTokenGenerator(new UuidCsrfTokenGenerator());
    return tokenRepo;
}

@Bean
public CsrfTokenRequestHandler csrfTokenRequestHandler() {
    // 使用默认处理器,避免异或校验逻辑
    return new DefaultCsrfTokenRequestHandler();
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.csrf(csrf -> csrf
            .csrfTokenRepository(tokenRepository())
            .csrfTokenRequestHandler(csrfTokenRequestHandler())
    );
    // 其他安全配置...
    return http.build();
}

方案2:使用Spring Security默认的Base64格式Token(推荐,符合新版本规范)

  1. 清除旧Cookie:手动清除浏览器中域名下的XSRF-TOKEN Cookie,避免残留的UUID格式干扰。
  2. 验证Token生成:前端发送GET请求(如首页接口),检查响应头的Set-Cookie,确认XSRF-TOKEN的值为Base64格式的长字符串(与你自定义端点返回的格式一致)。
  3. 确认Angular配置:确保HttpClientXsrfModule使用默认配置(无需额外修改),如果显式配置需保持与Spring一致:
    HttpClientXsrfModule.withOptions({
      cookieName: 'XSRF-TOKEN',
      headerName: 'X-XSRF-TOKEN'
    })
    
  4. 检查CORS配置:Spring Security需允许携带Cookie,Angular请求需设置withCredentials: true。

额外排查点

  • 检查项目中是否存在自定义的TokenGenerator Bean,覆盖了Spring Security的默认实现。
  • 确认前端请求的域名、路径与Spring的Cookie路径(/)匹配,避免Cookie无法被读取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:05:25