CookieAuthenticationOptions.AuthenticationType 用於什麼?
在我的應用程序的 Asp.Net Identity Auth 中間件設置中,我有
app.UseCookieAuthentication(new CookieAuthenticationOptions { LoginPath = new PathString("/Login/"), //AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<MyUserManager, MyUser>( TimeSpan.FromMinutes(30), (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie) ), }, });我從另一個應用程序中複製了這個,我只是注意到如果我取消註釋該
AuthenticationType行,登錄成功(我在我的記錄器中收到一條從我的控制器寫入的成功消息)但總是重定向回登錄螢幕。在CookieAuthenticationOptions 的文件中它說
選項中的 AuthenticationType 對應於 IIdentity AuthenticationType 屬性。為了在管道中多次使用相同的身份驗證中間件類型,可以分配不同的值。(繼承自 AuthenticationOptions。)
我真的不明白這意味著什麼,為什麼這會導致我的登錄請求被重定向(在成功登錄之後),也不知道這個選項有什麼用處。
這是一個字元串,可以是任何東西。但這是身份驗證類型的標識符。而且您可以有多種身份驗證類型:您的數據庫與使用者、Google、Facebook 等。據我所知,這是作為登錄時生成的 cookie 的聲明添加的。
當您註銷使用者時,您需要知道身份驗證提供程序。如果您的身份驗證中間件是這樣定義的:
app.UseCookieAuthentication(new CookieAuthenticationOptions { LoginPath = new PathString("/Login/"), AuthenticationType = "My-Magical-Authentication", // etc... }, });然後要註銷使用者,您需要相同的魔術字元串:
AuthenticationManager.SignOut("My-Magical-Authentication")此字元串也在
ClaimsIdentity創建主體時傳遞。沒有AuthenticationType主體就無法進行身份驗證,因為:/// <summary> /// Gets a value that indicates whether the identity has been authenticated. /// </summary> /// /// <returns> /// true if the identity has been authenticated; otherwise, false. /// </returns> public virtual bool IsAuthenticated { get { return !string.IsNullOrEmpty(this.m_authenticationType); } }此方法
IsAuthenticated用於整個 MVC 程式碼庫,所有身份驗證機制都依賴於此。同樣從理論上講,您可以通過多個提供商登錄,一次只註銷其中一個,其餘的提供商仍然經過身份驗證。雖然我從未嘗試過這個。
我剛剛發現的另一個用途 - 如果您沒有
CookieName在中間件配置中提供,那麼Options.CookieName = CookieAuthenticationDefaults.CookiePrefix + Options.AuthenticationType;(請參閱建構子中的第二個 if 語句)。我敢肯定還有更多地方使用它。但最重要的是提供它並與名稱保持一致,否則您會在身份驗證系統中遇到細微的錯誤。