OnValidateIdentity ASP.NET Identity如何工作

Use*_*987 2 c# asp.net cookies asp.net-mvc asp.net-identity

我试图更好地了解.NET的Identity OnValidateIdentity方法的工作原理。我已经在我的应用程序中设置了这段代码,如下所示:

app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        CookieName = "LoginCookie",
        ExpireTimeSpan = TimeSpan.FromHours(1),
        Provider = new CookieAuthenticationProvider
        {
            // Enables the application to validate the security stamp when the user logs in.
            // This is a security feature which is used when you change a password or add an external login to your account.  
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromHours(1),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
        }
    });
Run Code Online (Sandbox Code Playgroud)

OnValidateIdentity是否在这里起到检查用户何时访问我的网站的作用,以查看其Cookie的年龄以及是否比我在此处设置的Cookie的年龄(1小时)大-用户将被迫重新登录。应用程序。

这到底是怎么运作的?

tra*_*max 6

如果您想更全面地理解,为什么不阅读源代码

简而言之,此方法将检查用户记录上的SecurityStamp的值是否已更改。它将每小时检查一次(在您的设置中)。因此,如果SecurityStamp已更改,则cookie无效。如果SecurityStamp自上次检查以来未更改,则cookie的值将更新(带有新的时间戳),但不会注销用户。

当用户更改密码并希望使所有浏览器中的所有现有auth-cookie无效时,此功能很有用。

在我的博客文章中有更多细节。