在 ASP.NET CORE 3.1 MVC 中实施 "Remember me"
Implement "Remember me" in 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 事件中。你能帮我说清楚吗?
谢谢!!
您可以通过以下方式获取 cookie 过期时间:context.Properties.ExpiresUtc
。
如果你想在登录成功后在另一个请求中获取过期时间,你可以将过期时间添加到ValidatePrincipal
中的HttpContext method.Once你登录成功并进入另一个操作,它将点击 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...
}
}
根据我的代码,我不知道如何在登录网站 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 事件中。你能帮我说清楚吗? 谢谢!!
您可以通过以下方式获取 cookie 过期时间:context.Properties.ExpiresUtc
。
如果你想在登录成功后在另一个请求中获取过期时间,你可以将过期时间添加到ValidatePrincipal
中的HttpContext method.Once你登录成功并进入另一个操作,它将点击 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...
}
}