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

使用Identity Server与.NET 6时关闭浏览器后用户自动登出问题

解决关闭浏览器后重新打开无法保持Identity Server登录状态的问题

你的问题根源在于当前配置的认证Cookie是会话Cookie,关闭浏览器后会被自动清除,同时令牌生命周期的配置也没有适配持久化登录的需求。以下是针对性的修改方案:

1. 配置持久化认证Cookie

修改AddCookie的配置,启用持久化Cookie并设置有效期:

.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
    options.ReturnUrlParameter = "requestedUrl";
    // 将Cookie标记为持久化,关闭浏览器后不会自动清除
    options.Cookie.IsPersistent = true;
    // 设置Cookie的有效期(例如7天,可根据需求调整)
    options.ExpireTimeSpan = TimeSpan.FromDays(7);
    // 启用滑动过期:用户每次活跃操作时自动延长Cookie有效期
    options.SlidingExpiration = true;
    // 确保Cookie的MaxAge与有效期一致
    options.Cookie.MaxAge = options.ExpireTimeSpan;
})

2. 调整OpenIdConnect令牌生命周期配置

默认情况下,UseTokenLifetime为true,会让认证Cookie的有效期与ID Token一致(通常较短,比如30分钟),需要禁用这个设置,改用自定义的Cookie有效期,同时配置自动刷新令牌:

.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    // 保留原有其他配置
    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.Authority = "IdentityServer";
    options.ResponseType = OidcConstants.ResponseTypes.CodeIdToken;
    options.ClientId = "IdentityClientId";
    options.ClientSecret = "IdentityClientSecret";
    options.RequireHttpsMetadata = false;
    options.SignedOutRedirectUri = websiteSettings.Home;
    options.GetClaimsFromUserInfoEndpoint = true;
    options.Scope.Add("ordering-api");
    options.Scope.Add("offline_access");
    options.SaveTokens = true;
    options.RemoteAuthenticationTimeout = TimeSpan.FromMinutes(30);
    options.TokenValidationParameters.RoleClaimType = "role";

    // 禁用使用Token的生命周期,改用Cookie配置的有效期
    options.UseTokenLifetime = false;
    // 设置自动刷新令牌的间隔(在Token过期前5分钟触发刷新)
    options.AutomaticRefreshInterval = TimeSpan.FromMinutes(25);
    // 设置令牌刷新的最长有效期(与Cookie有效期保持一致)
    options.AbsoluteRefreshInterval = TimeSpan.FromDays(7);

    options.Events = new OpenIdConnectEvents
    {
        // 保留原有事件
    };
})

3. 确保登录时标记会话为持久化

在执行登录操作时,明确设置IsPersistent为true,确保会话持久化:

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    userPrincipal,
    new AuthenticationProperties
    {
        IsPersistent = true,
        ExpiresUtc = DateTimeOffset.UtcNow.AddDays(7) // 与Cookie有效期一致
    });

4. 验证Identity Server客户端配置

确保你的Identity Server客户端配置中,OfflineAccessAllowed已设置为true,否则不会返回Refresh Token,无法实现持久化登录:

// Identity Server客户端配置示例
new Client
{
    ClientId = "IdentityClientId",
    ClientSecrets = { new Secret("IdentityClientSecret".Sha256()) },
    // 其他配置
    AllowedScopes = { "openid", "profile", "ordering-api", "offline_access" },
    OfflineAccessAllowed = true // 必须启用这个选项
}

完成以上配置后,用户关闭浏览器再重新打开时,持久化Cookie会保留,系统会自动使用Refresh Token获取新的令牌,从而保持登录状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 19:23:23