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

.NET Core(Blazor)中登录会话过期异常问题

问题:Cookie认证设置12小时过期,但20-30分钟后自动登出

我在登录时将Cookie过期时间设置为12小时,但实际会在20或30分钟后被登出并跳转至登录页面。以下是我的登录代码:

List<Claim> claims = new List<Claim>{
    new Claim(ClaimTypes.Email, user.Email),
    new Claim(ClaimTypes.Name, FullName),
    new Claim(ClaimTypes.Surname, user.Username),
    new Claim(ClaimTypes.UserData, "Active"),
    new Claim(ClaimTypes.Sid, user.UserId.ToString()),
};
AuthenticationProperties authProperties = new AuthenticationProperties
{
    IsPersistent = true,
    ExpiresUtc = DateTime.UtcNow.AddHours(12),
    AllowRefresh = true,
};
ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal cp = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, cp, authProperties);

注:截图显示Cookie的过期时间已设置为UTC时间12小时,但实际仍会提前登出,期望实现12小时后自动登出。


可能的原因及解决方法

1. 全局Cookie认证配置覆盖局部设置

如果在Startup.cs或Program.cs中配置CookieAuthenticationOptions时设置了较短的ExpireTimeSpan,会覆盖你在SignInAsync时设置的AuthenticationProperties。比如:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(20); // 该设置会覆盖局部的12小时配置
        // 其他配置项
    });

解决方法:

  • 将全局的ExpireTimeSpan调整为TimeSpan.FromHours(12),与局部设置保持一致;
  • 若需保留全局默认值,确保IsPersistent = true(你已设置),此时局部的ExpiresUtc优先级高于全局ExpireTimeSpan(部分.NET版本需确认此逻辑)。

2. 滑动过期(SlidingExpiration)逻辑干扰

默认情况下SlidingExpiration为true,若全局配置中ExpireTimeSpan设置较短,即使你指定了绝对过期时间ExpiresUtc,滑动过期逻辑可能会提前刷新Cookie的过期时间(或在无操作时提前失效)。

解决方法:

  • 在全局Cookie配置中禁用滑动过期:options.SlidingExpiration = false;,确保绝对过期时间生效;
  • 若需保留滑动过期,将全局ExpireTimeSpan设置为12小时,同时ExpiresUtc也设为12小时,避免冲突。

3. Session超时影响(若使用Session存储认证票据)

如果你的应用配置了Session,并将认证票据存储在Session中(如使用SessionTicketStore),Session的IdleTimeout设置较短会导致认证Cookie提前失效。比如:

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(20); // 此设置会影响Session存储的认证票据
});

解决方法:

  • 将Session的IdleTimeout延长至12小时;
  • 改用分布式缓存(如Redis)存储认证票据,避免依赖Session。

4. 浏览器或第三方工具清理Cookie

部分浏览器的隐私模式、插件或安全软件会自动清理会话Cookie,即使设置了持久Cookie。
解决方法:

  • 在普通浏览器模式下测试,关闭隐私保护插件;
  • 检查浏览器的Cookie保留策略,确保允许持久Cookie存储。

5. 代码笔误

你的代码中awaitHttpContext.SignInAsync存在拼写错误(缺少空格),正确写法应为await HttpContext.SignInAsync。若实际代码如此,会导致编译错误,但如果是输入时的笔误,需确保运行代码无语法错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:13:26