OnValidateIdentity ASP.NET身份如何工作

时间:2017-02-17 16:29:29

标签: c# asp.net asp.net-mvc cookies 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))
        }
    });

此处的OnValidateIdentity是否有权检查用户何时访问我的网站以查看他的Cookie年龄,以及它是否比我在此处设置的更早(1小时) - 用户将被迫重新进入应用程序。

这是它的工作原理吗?

1 个答案:

答案 0 :(得分:5)

如果您想获得更全面的理解,为什么不阅读source code

简而言之,此方法将检查用户记录上的SecurityStamp值是否已更改。它将每小时进行检查(在您的设置中)。因此,如果SecurityStamp已更改,则cookie将失效。如果SecurityStamp在上次检查时没有变化,则更新cookie的值(使用新的时间戳)但用户未注销。

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

blog post中的更多细节。