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

页面刷新后Authentication Cookie失效问题排查求助

问题分析与修复方案

你的问题核心是认证方案配置冲突,导致刷新页面时认证逻辑失效,具体原因和修复步骤如下:

1. 默认认证方案设置错误

你把默认的DefaultAuthenticateScheme和DefaultChallengeScheme都设成了JwtBearerDefaults.AuthenticationScheme,但实际你主要依赖Cookie认证。每次请求会优先用JwtBearer去验证,而你在Jwt的OnMessageReceived里拿了名为access_token的Cookie——但这个Cookie是Cookie认证生成的票据,不是标准JWT格式,导致Jwt认证直接失败,触发挑战逻辑跳转到登录页。

2. Cookie名称与Jwt Token键冲突

你把Cookie的名字也设为access_token,和Jwt要读取的Token键重名,进一步加剧了认证逻辑的混乱。


修复后的代码示例

ConfigureServices 部分修改

services
.AddAuthentication(o =>
{
    // 把默认认证/挑战方案改成Cookie认证
    o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    o.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =>
{
    o.SaveToken = true;
    o.Events = new JwtBearerEvents()
    {
        OnMessageReceived = context =>
        {
            // 如果需要同时支持Jwt,建议换个键名,比如"jwt_token"
            context.Token = context.Request.Cookies["jwt_token"];
            return Task.CompletedTask;
        }
    };
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
    // 修改Cookie名称,避免和Jwt的Token键冲突
    options.Cookie.Name = "AuthCookie";
    options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.SecurePolicy = CookieSecurePolicy.None;
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.LoginPath = "/signin";
    options.LogoutPath = "/signout";
});

// 如果需要同时支持两种认证方案的授权策略,保留这段;如果只用Cookie,可简化
var multiSchemePolicy = new AuthorizationPolicyBuilder(
        CookieAuthenticationDefaults.AuthenticationScheme,
        JwtBearerDefaults.AuthenticationScheme)
    .RequireAuthenticatedUser()
    .Build();

额外注意事项

  • 登录时必须使用Cookie认证方案完成登录操作,示例代码:
    // 生成用户身份凭证(principal)后,调用Cookie认证的SignInAsync
    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal);
    
  • 如果不需要同时支持Jwt认证,可以直接移除AddJwtBearer相关配置,进一步简化逻辑。

内容的提问来源于stack exchange,提问作者Zygmunt Kołodziejczyk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:15:26