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

React应用使用JWT Token通过Axios请求时返回401错误

问题

使用Axios调用Web API时返回401认证错误,但Swagger和Postman调用相同接口完全正常,具体情况:

  • Web API的Authentication模块生成JWT Token返回给客户端,客户端将Token存在sessionStorage中
  • 携带Bearer Token调用API接口时,返回401错误

Axios请求代码

getPatients: async (token: string): Promise<PatientDTO[]> => {
try {
  const response: AxiosResponse<PatientDTO[]> = await axios.get(
    `${API_BASE_URL}/patient`,
    {
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
    }
  );

  const patients = response.data.map((patient) => ({
    ...patient,
  }));

  return patients;
} catch (error) {
  console.log("Error fetching patients:", error);
  throw error;
}
},

API配置代码

CORS配置

services.AddCors(opt =>
{
opt.AddPolicy("CorsPolicy", policy =>
{
    policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
});
});

JWT认证配置

.AddAuthentication(item =>
{
    item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    item.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = false,
        IssuerSigningKey = new SymmetricSecurityKey
      (Encoding.UTF8.GetBytes(config["Jwt:Key"]))
    };
});

错误信息

请求返回401 Unauthorized,认证失败。


排查与解决方法
  • 核对Token完整性:在Axios发起请求前打印token值,和Swagger/Postman中使用的Token逐字符对比,确认没有多余空格、换行或截断。sessionStorage存取值时可能出现意外的字符串处理,直接console.log(token)就能快速验证。
  • 检查请求头格式:确保Authorization头是Bearer + 空格 + Token的格式,不要漏掉空格。打开浏览器开发者工具的Network面板,查看实际发送的请求头,和Postman的请求头做对比。另外GET请求不需要Content-Type头(无请求体),可以尝试去掉该头,避免潜在冲突。
  • 验证Token有效期:用JWT解码工具解析Token,查看exp字段对应的过期时间是否在当前时间之后,排除Token过期导致的401。
  • 确认中间件顺序:ASP.NET Core中中间件顺序直接影响功能,必须保证app.UseCors("CorsPolicy")在app.UseAuthentication()和app.UseAuthorization()之前执行,否则CORS头无法正确返回,浏览器会拦截请求。
  • 修正JWT配置逻辑:当前配置中ValidateIssuerSigningKey设为false但又指定了IssuerSigningKey,逻辑矛盾。尝试将ValidateIssuerSigningKey改为true,确保签名验证正常执行——Swagger/Postman可能因为某些绕过逻辑正常,但客户端请求会因签名验证不通过被拒绝。
  • 排除浏览器缓存干扰:清空浏览器缓存或用隐私模式测试,避免旧的请求头、Cookie缓存导致的认证失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 20:00:26