小编axu*_*uno的帖子

使用ASP.NET Core 2.1身份验证身份验证cookie

在ASP.NET Core 2(带有或不带有Identity)中使用Cookie身份验证时,可能会发生以下情况:更改用户的电子邮件或名称,甚至在cookie的生存期内删除帐户。这就是为什么文档指出cookie应该被验证的原因。文档中的示例带有注释

此处描述的方法是在每个请求上触发的。这可能会导致应用程序性能下降。

所以我想知道验证cookie主体的最佳模式什么。我所做的Startup.cs是订阅OnValidatePrincipal事件并通过例如LastValidatedOn对cookie 附加声明来每隔5分钟检查一次主记录的有效性:

services.ConfigureApplicationCookie(options =>
{
    // other cookie options go here

    options.Events.OnValidatePrincipal = async context =>
    {
        const string claimType = "LastValidatedOn";
        const int reValidateAfterMinutes = 5;

        if (!(context.Principal?.Identity is ClaimsIdentity claimIdentity)) return;

        if (!context.Principal.HasClaim(c => c.Type == claimType) ||
            DateTimeOffset.Now.UtcDateTime.Subtract(new DateTime(long.Parse(context.Principal.Claims.First(c => c.Type == claimType).Value))) > TimeSpan.FromMinutes(reValidateAfterMinutes))
        {
            var mgr = context.HttpContext.RequestServices.GetRequiredService<SignInManager<ApplicationUser>>();
            var user = await mgr.UserManager.FindByNameAsync(claimIdentity.Name);
            if (user != null …
Run Code Online (Sandbox Code Playgroud)

c# cookies asp.net-core asp.net-core-identity

7
推荐指数
1
解决办法
3361
查看次数

标签 统计

asp.net-core ×1

asp.net-core-identity ×1

c# ×1

cookies ×1