asp.net-core-mvc - 在 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
。
如果你想在登录成功后获取其他请求中的过期时间,可以在方法中将过期时间添加到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...
}
}
推荐阅读
- swagger - swagger 是否仍可用于生成 Swagger 2 文档而不是 OAS3?
- angular - 将管道输出另存为变量
- javascript - 使用授权标头获取请求在 React 中不起作用
- python - 如何修复 AttributeError:在 pandas 中加载 excel 文件时“int”对象没有属性“strip”
- mysql - 带别名的 NodeJS 复杂 Mysql 查询?
- java - 将页脚和页眉添加到将用于创建 excel 文件 (xls) 的 xsl 文件
- python - Matplotlib 在多个子图上绘制文本 - 如何选择哪个子图?
- distributed-system - 服务器如何发现 gossip 成员协议中的现有成员?
- powershell - 在powershell中使用“foreach”循环将内容写入文件
- azure - AAD 安全组问题 技术问题