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

问题描述 投票:7回答:1

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

这里描述的方法是在每个请求上触发的。这个可以会导致该应用的性能下降。

所以我想知道什么是验证Cookie主体的最佳模式?>>。我在Startup.cs中所做的工作是订阅OnValidatePrincipal事件并检查主数据的有效性,例如每5分钟在Cookie上附加LastValidatedOn声明,如下所示:

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 && claimIdentity.Claims.FirstOrDefault(c => c.Type == "AspNet.Identity.SecurityStamp")?.Value == await mgr.UserManager.GetSecurityStampAsync(user))
            {
                claimIdentity.FindAll(claimType).ToList().ForEach(c => claimIdentity.TryRemoveClaim(c));
                claimIdentity.AddClaim(new Claim(claimType, DateTimeOffset.Now.UtcDateTime.Ticks.ToString(), typeof(long).ToString()));
                context.ShouldRenew = true;
            }
            else
            {
                context.RejectPrincipal();
                await mgr.SignOutAsync();
            }
        }
    };
});

[在ASP.NET Core 2中使用Cookie身份验证(带有或不带有身份)时,可能会发生以下情况:更改用户的电子邮件或名称,甚至在cookie的生存期内删除帐户。那是...

c# asp.net-core cookies asp.net-core-3.1 asp.net-core-identity
1个回答
12
投票

@@ MarkG为我指明了正确的方向,谢谢。在仔细研究了the source codeSecurityStampValidatorIdentity之后,对我来说,事情变得很清楚。实际上,我发布的问题的示例代码是不必要的,因为ASP.NET Core Identity可以以更好的方式立即使用该功能。

由于我还没有找到这样的摘要,也许对其他人也有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.