实现“记住我"在 ASP.NET 核心 3.1 MVC 中 [英] Implement "Remember me" in ASP.NET CORE 3.1 MVC

查看:80
本文介绍了实现“记住我"在 ASP.NET 核心 3.1 MVC 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can't figure out how to add the functionality of "Remember me" while logging in the website ASP.NET CORE 3.1 MVC according to the code I have below. Where and how should I check if the session on server side has expired and, in this case, load the user info from the DB according to the cookie?

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

使用记住我"登录时在服务器端执行的代码检查:

Code executed server side when logging with "Remember me" checked:

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 我有:

In the Startup.cs I have:

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 事件中.你能帮我说清楚吗?谢谢!!

My guess would be in the CookieAuthenticationEvents.OnSigningIn event. Can you help me to make it clear? Thank you!!

推荐答案

您可以通过使用:context.Properties.ExpiresUtc 来获取 cookie 的过期时间.

You could get the cookie expire time by using:context.Properties.ExpiresUtc.

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

If you want to get the expire time in the other request after login successfully,you could add the expire time to HttpContext in ValidatePrincipal method.Once you sign in successfully and get into another action,it will hit the ValidatePrincipal method to add the expire time to HttpContext.

自定义 CookieAuthenticationEvents:

Custom CookieAuthenticationEvents:

public class MyCookieAuthenticationEvents : CookieAuthenticationEvents
{

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

    }
}

获取动作中的过期时间:

Get the expire time in the action:

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

结果:

更新:

如何判断cookie过期:

For how to judge the cookie expired:

 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...
    }

}

这篇关于实现“记住我"在 ASP.NET 核心 3.1 MVC 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆