React+Spring Boot项目中POST请求的CSRF令牌添加与认证问题
解决React与Spring Boot POST请求的CSRF认证问题
核心问题:请求头名称不匹配
Spring Security默认期望的CSRF请求头是X-XSRF-TOKEN,而非你当前使用的X-CSRF-TOKEN,这是导致403响应的最常见原因,先修正这个关键点:
let csrfToken = getCookie("XSRF-TOKEN"); console.log("testing csrf token: " + csrfToken); const res = await fetch(`/register`, { method: "POST", credentials: "include", // 前后端分离场景必须添加,确保请求携带Cookie headers: { "Content-Type": "application/json", "X-XSRF-TOKEN": csrfToken, // 改为Spring Security默认识别的头名称 }, body: JSON.stringify({ firstName: firstName, lastName: lastName, mobileNumber: mobileNumber, email: email, password: password, }), });
补充排查与配置项
确认Spring Security完整配置
确保配置类中不仅开启了CSRF,还正确配置了CORS以支持跨域携带Cookie:@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) ) .authorizeHttpRequests(auth -> auth .requestMatchers("/register").permitAll() .anyRequest().authenticated() ) .cors(cors -> cors.configurationSource(corsConfigurationSource())); // 启用CORS配置 return http.build(); } // 跨域配置:允许React前端地址携带Cookie @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(List.of("http://localhost:3000")); // 替换为你的React服务地址 config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE")); config.setAllowedHeaders(List.of("*")); config.setAllowCredentials(true); // 关键:允许请求携带Cookie UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } }确保请求前已获取CSRF Cookie
Spring Security仅在首次收到请求时生成CSRF Cookie,若React直接发送POST请求可能尚未拿到令牌。可在应用初始化时先发送一个简单GET请求触发Cookie生成:// 放在React根组件的useEffect中执行 useEffect(() => { fetch("/", { credentials: "include" }) .then(() => console.log("CSRF Cookie已获取")) .catch(err => console.error("获取CSRF Cookie失败:", err)); }, []);验证令牌获取逻辑
打开浏览器开发者工具的Application > Cookies,确认XSRF-TOKEN存在,同时对比控制台打印的令牌值与Cookie中的值是否一致,排查获取逻辑是否正常。
总结
优先修正请求头名称为X-XSRF-TOKEN,同时确保请求携带credentials: "include",再检查CORS配置是否允许跨域携带Cookie,这些步骤可解决绝大多数CSRF认证导致的403问题。
内容的提问来源于stack exchange,提问作者Lariz14
相关产品推荐
相关产品推荐

