首页 > 解决方案 > 在 ASP.NET CORE 3.1 MVC 中实现“记住我”

问题描述

根据我下面的代码,在登录网站 ASP.NET CORE 3.1 MVC 时,我无法弄清楚如何添加“记住我”的功能。我应该在哪里以及如何检查服务器端的会话是否已过期,在这种情况下,根据 cookie 从数据库加载用户信息?

实际示例: 用户登录(选中“记住我”)并在 1 周后返回网站。同时,服务器上的会话已过期。我希望用户回来时自动登录。

使用“记住我”进行日志记录时在服务器端执行的代码已选中:

var userClaims = new List<Claim>()
{
     new Claim("id", user.Id.ToString()),
     new Claim("id_organisation", user.Id_organisation.ToString())
};

var grantMyIdentity = new ClaimsIdentity(userClaims, "User Identity");
var userPrincipal = new ClaimsPrincipal(new[] { grantMyIdentity });
await HttpContext.SignInAsync(userPrincipal, new AuthenticationProperties
{
       IsPersistent = true,
       ExpiresUtc = DateTime.UtcNow.AddMonths(1)                          
});

在 Startup.cs 我有:

public void ConfigureServices(IServiceCollection services)
{
     ...
     TimeSpan expiration_cookie_and_session = TimeSpan.FromHours(2);
     services.AddAuthentication("CookieAuthentication")
             .AddCookie("CookieAuthentication", config =>
              {
                  config.Cookie.Name = "UserLoginCookie";
                  config.LoginPath = "/connexion";
                  config.SlidingExpiration = true;
                  config.ExpireTimeSpan = expiration_cookie_and_session;
                  config.EventsType = typeof(MyCookieAuthenticationEvents);
              });
     services.AddScoped<MyCookieAuthenticationEvents>();
     services.AddSession(options => {
              options.IdleTimeout = expiration_cookie_and_session;
         });
      ...
 }

public class MyCookieAuthenticationEvents : CookieAuthenticationEvents
{
    //We are here in case of cookie expiration
    public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> redirectContext)
    {
     ...
    }
}

我的猜测是在 CookieAuthenticationEvents.OnSigningIn 事件中。你能帮我说清楚吗?谢谢!!

标签: asp.net-core-mvcsession-cookiesclaims-based-identity

解决方案


您可以使用以下方法获取 cookie 过期时间:context.Properties.ExpiresUtc

如果你想在登录成功后获取其他请求中的过期时间,可以在方法中将过期时间添加到HttpContext中ValidatePrincipal。一旦登录成功并进入另一个动作,它会点击ValidatePrincipal方法将过期时间添加到HttpContext .

自定义 CookieAuthenticationEvents:

public class MyCookieAuthenticationEvents : CookieAuthenticationEvents
{

    public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
    {
        context.Request.HttpContext.Items.Add("ExpiresUTC", context.Properties.ExpiresUtc);

    }
}

获取动作中的过期时间:

public async Task<IActionResult> Index()
{
    var expiretime = HttpContext.Items["ExpiresUTC"];
              
    return View();
}

结果:

在此处输入图像描述

更新:

关于如何判断cookie过期:

 public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
{

    context.Request.HttpContext.Items.Add("ExpiresUTC", context.Properties.ExpiresUtc);
    //Compare() method Return value Meaning
    //Less than zero means first is earlier than second. 
    //Zero means first is equal to second. 
    //Greater than zero means first is later than second.
    var calculte = DateTimeOffset.Compare((DateTimeOffset)context.Properties.ExpiresUtc, DateTimeOffset.Now);
    if(calculte<0)
    {
        // the cookie has been expired
        //do your stuff...
    }

}

推荐阅读