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

RESTful服务返回401错误排查:Spring Security与React集成问题

更新

在调试日志的帮助下,我发现问题在于Spring提示notices控制器存在无效的CSRF令牌。目前我已对比Postman和fetch请求生成的请求头,未发现差异,生成的令牌已成功放入请求头中。但Spring日志中没有更多可排查信息,调试仍在进行。


问题描述

我正在学习Spring Security,当前正在将React前端与Spring后端进行集成。遇到的问题是:向目标端点发送POST请求时,返回401错误。这让我感到困惑,因为我认为自己已正确配置CORS,并且将相关端点标记为permitAll。

简要流程如下:先调用/token端点获取CSRF令牌,再调用/notices端点并在请求头中传入该令牌。使用Postman执行该流程时一切正常,因此我曾以为是CORS问题,但将前端运行在其他端口时会被CORS阻止,所以我认为问题出在别处。

补充信息

  • /notices和/token均为POST操作。
  • Spring后端与React前端运行在同一本地机器上。
  • 收到的错误码为401。

前端JavaScript调用代码

const debugNotices = () => {
  let tokenData:any;
  fetch('http://localhost:8080/token', {method:"POST"})
  .then((response) => response.json())
  .then((data) => tokenData = data).then((data:any) => fetch("http://localhost:8080/notices", 
  {
    method:"POST",
    headers: {
      "X-XSRF-TOKEN": tokenData.token
    }
  }))

}

Spring Security配置

@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        
    http
        .cors()
            .configurationSource(new CorsConfigurationSource() {
            
                @Override
                public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
                    CorsConfiguration config = new CorsConfiguration();
                    
                    config.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
                    config.setAllowedMethods(Collections.singletonList(("*")));
                    config.setAllowCredentials(true);
                    config.setAllowedHeaders(Collections.singletonList("*"));
                    config.setMaxAge(3600L);
                    return config;
                }
            })
            .and()
        .csrf()
            .ignoringRequestMatchers("/contact", "/register", "/token")
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) 
            .and()
        .securityContext()
            .requireExplicitSave(false)
            .and()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            .and()
        .authorizeHttpRequests()
            .requestMatchers("/myAccount", "/myBalance", "/myLoans", "/myCards", "/user").authenticated()
            .requestMatchers("/notices", "/contact", "/register", "/test", "/token").permitAll()
            .and()
        .httpBasic()
            .and()
        .formLogin();
        
    return http.build();
}

已尝试的解决方法

  • 在请求中加入credentials:'include',但弹出登录提示,不符合预期。
  • 手动插入CSRF令牌而非从服务器获取,结果同样失败。
  • 测试CORS:从localhost:3000以外的地址访问端点会被CORS阻止,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:05:15