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

ASP.NET Core 5 MVC迁移至Identity后如何延长用户有效期?

延长ASP.NET Identity用户登录有效期的方法

在ASP.NET Core 5中,用户登录状态的有效期由认证Cookie控制,你可以通过配置Cookie选项来调整时长。基于你的现有Startup代码,修改方式如下:

services.AddIdentity<ApplicationUser, IdentityRole>(option => 
{
    option.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ProjectDbContex>()
.AddDefaultTokenProviders()
.AddErrorDescriber<PersianIdentityErrorDescriber>()
// 配置认证Cookie的有效期
.ConfigureApplicationCookie(options =>
{
    // 设置Cookie绝对过期时间,示例为30天
    options.ExpireTimeSpan = TimeSpan.FromDays(30);
    // 开启滑动过期:用户活跃时自动刷新Cookie有效期
    options.SlidingExpiration = true;
    // 可选:指定登录跳转路径(根据你的项目调整)
    options.LoginPath = "/Account/Login";
});

核心配置说明:

  • ExpireTimeSpan:设置Cookie的绝对过期时长,比如TimeSpan.FromHours(12)表示12小时后失效,TimeSpan.FromMonths(1)表示1个月后失效,按需调整即可。
  • SlidingExpiration:设为true时,用户每次发起请求(活跃操作)都会刷新Cookie的过期时间,避免用户在使用过程中被强制登出。

区分"普通登录"与"记住我"的有效期(可选)

如果需要给勾选"记住我"的用户设置更长的有效期,可以在登录逻辑中手动指定认证属性:

// 假设这是你的登录Action代码片段
var signInResult = await _signInManager.PasswordSignInAsync(
    model.Email, 
    model.Password, 
    isPersistent: model.RememberMe, 
    lockoutOnFailure: false
);

if (signInResult.Succeeded)
{
    var authProps = new AuthenticationProperties
    {
        // 记住我时设为1个月,否则设为1天
        ExpiresUtc = model.RememberMe 
            ? DateTimeOffset.UtcNow.AddMonths(1) 
            : DateTimeOffset.UtcNow.AddDays(1),
        IsPersistent = model.RememberMe,
        AllowRefresh = true
    };

    await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, User, authProps);
    return RedirectToAction("Index", "Home");
}

注意要点:

  • 过长的有效期会增加账号被盗用的风险,建议根据业务场景合理设置,比如内部系统可适当延长,公开面向用户的系统建议控制在1-7天内。
  • 如果你的项目同时配置了AddAuthentication,ConfigureApplicationCookie会自动覆盖默认的Cookie认证配置,无需额外冲突处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:50:17