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

.NET 6应用中活跃用户自动登出问题的解决方法咨询

解决.NET 6活跃用户自动登出问题

1. 启用认证Cookie滑动过期

这是解决活跃用户登出问题的核心配置,需要在Program.cs中确保认证Cookie开启滑动过期,并设置合理的总过期时长:

如果使用原生Cookie认证:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromHours(8); // 设置用户无操作时的最大过期时长
        options.SlidingExpiration = true; // 开启滑动过期:用户活跃时自动延长Cookie有效期
        options.Cookie.HttpOnly = true;
        options.Cookie.SameSite = SameSiteMode.Lax; // 适配AJAX请求的Cookie携带规则
    });

如果使用ASP.NET Identity:

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

// 单独配置Identity的认证Cookie
builder.Services.ConfigureApplicationCookie(options =>
{
    options.ExpireTimeSpan = TimeSpan.FromHours(8);
    options.SlidingExpiration = true;
    options.Cookie.HttpOnly = true;
    options.Cookie.SameSite = SameSiteMode.Lax;
});

2. 确保AJAX请求携带认证Cookie

如果你的应用存在跨域AJAX请求,需要同时配置后端CORS和前端请求参数:

后端CORS配置

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowFrontend", policy =>
    {
        policy.WithOrigins("https://your-frontend-domain.com") // 替换为实际前端域名
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials(); // 允许请求携带认证Cookie
    });
});

// 中间件顺序注意:放在UseRouting之后,UseAuthorization之前
app.UseCors("AllowFrontend");

前端请求配置

  • jQuery示例:
$.ajax({
    url: "/api/your-endpoint",
    type: "POST",
    xhrFields: { withCredentials: true }, // 携带Cookie
    data: yourData
});
  • Fetch API示例:
fetch("/api/your-endpoint", {
    method: "POST",
    credentials: "include", // 携带Cookie
    body: JSON.stringify(yourData)
});

3. 同步Session配置(若使用Session)

如果应用依赖Session,需确保Session的过期时间与认证Cookie一致,且开启滑动过期:

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromHours(8); // 和认证Cookie过期时长保持一致
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

// 中间件放在UseRouting之后,UseAuthorization之前
app.UseSession();

4. 修正Login方法的认证票配置

在登录逻辑中,确保生成的认证属性与全局配置匹配,允许刷新并设置持久化:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, user.UserName),
    // 添加其他必要声明
};

var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties
{
    ExpiresUtc = DateTimeOffset.UtcNow.AddHours(8),
    IsPersistent = true, // 若提供"记住我"选项,可根据用户选择动态设置
    AllowRefresh = true // 允许刷新认证票,配合滑动过期生效
};

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    authProperties);

5. 适配HTTPS环境的Cookie配置

如果应用部署在HTTPS环境,需确保Cookie的Secure属性开启,避免浏览器拒绝保存或发送Cookie:

options.Cookie.SecurePolicy = CookieSecurePolicy.Always;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 18:40:56