2017-02-17 85 views
1

我想更好地瞭解.NET的Identity OnValidateIdentity方法是如何工作的。我已成立了這段代碼在我的應用程序類似以下內容:OnValidateIdentity ASP.NET Identity如何工作

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小時) - 用戶將被迫重新登錄到應用程序中。

這是如何工作的?

回答

3

那麼,爲什麼不自己讀source code以獲得充分的理解?

簡而言之,此方法將檢查用戶記錄上SecurityStamp的值是否已更改。它會每小時檢查一次(在你的設置中)。所以如果SecurityStamp發生了變化,這個cookie就會失效。如果SecurityStamp與上次檢查時保持不變,則會更新cookie的值(使用新時間戳),但用戶未註銷。

此功能在用戶更改密碼並想要使所有瀏覽器中的所有現有auth-cookie無效時很有用。我的blog post更詳細一點。