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

ReactJS调用.NET Core API时Cookie未保存致401授权失败求助

问题解决:React Axios跨域登录后Cookie未保存导致401

核心问题分析

你的场景是跨域(前端http://localhost:3000,后端https://localhost:7072)下的Cookie认证,出现Cookie未保存、后续请求401的原因集中在Axios配置错误、Cookie属性缺失、CORS冗余配置三个方面。


解决方案步骤

1. 修正Axios请求的withCredentials位置

Axios的post方法参数顺序是url, data, config,你当前把withCredentials放在了data参数位置,导致配置未生效。修改登录请求:

login = (login, password) => {
    axios
        // 第二个参数传null(无请求体),第三个参数放配置
        .post(`https://localhost:7072/auth/login?Login=${login}&Password=${password}`, null, { withCredentials: true })
        .then(response => {
            if (response.status === 200) {
                console.log(response);
                // 后续GET请求也要带withCredentials
                this.fetchUser();
            }
        })
        .catch(error => {
            console.log(error);
        });
}

// 新增的获取用户信息方法,必须带withCredentials
fetchUser = () => {
    axios.get(`https://localhost:7072/auth/get`, { withCredentials: true })
        .then(res => console.log(res.data))
        .catch(err => console.log(err));
}

2. 后端Cookie配置添加Secure属性

当SameSite=None时,浏览器要求Cookie必须设置Secure属性(仅在HTTPS下传输),否则会拒绝保存。修改program.cs中的Cookie配置:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.Cookie.SameSite = SameSiteMode.None;
        options.Cookie.Secure = true; // 新增这一行
        options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
    });

3. 优化CORS配置,移除冗余项

你的CORS配置中SetIsOriginAllowedToAllowWildcardSubdomains和WithExposedHeaders("Access-Control-Allow-Origin")是多余的,且可能引发冲突。简化配置:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowLocalhost3000",
        config =>
        {
            config.WithOrigins("http://localhost:3000")
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials();
        });
});

验证步骤

  1. 登录后打开浏览器开发者工具,进入Application -> Cookies -> https://localhost:7072,确认是否存在认证Cookie,且属性包含HttpOnly、Secure、SameSite=None。
  2. 查看后续GET请求的Request Headers,确认是否携带了Cookie字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:03:16