Asp.net

身份 cookie 在一段時間後失去自定義聲明資訊

  • May 13, 2014

我將自定義聲明(例如使用者的真實姓名)儲存在 ASP.NET 身份 cookie 中,以避免對每個請求進行不必要的數據庫查詢。至少這就是我認為這段程式碼正在做的事情:

var identity = await user.GenerateUserIdentityAsync(UserManager);
identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName)));
// etc.
AuthenticationManager.SignIn(new AuthenticationProperties {IsPersistent=true}, identity);

這很好用,我可以通過以下方式檢索這些聲明:

private static string GetClaim(string claimType)
{
 var identity = (ClaimsPrincipal) Thread.CurrentPrincipal;
 var claim = identity.Claims.SingleOrDefault(o => o.Type == claimType);
 return claim == null ? null : claim.Value;
}

正如預期的那樣,該identity.Claims屬性包含以下聲明:

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: ced2d16c-cb6c-4af0-ad5a-09df14dc8207
http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: me@example.com
http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider: ASP.NET Identity
AspNet.Identity.SecurityStamp: 284c648c-9cc7-4321-b0ce-8a347cd5bcbf
http://schemas.microsoft.com/ws/2008/06/identity/claims/role: Admin
http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname: My Name

麻煩的是,一段時間後(通常是幾個小時),我的自定義聲明似乎消失了——在這個例子givenname中,列舉中不再存在。使用者仍然經過身份驗證,所有預設聲明仍然存在。

發生了什麼事,我該如何解決這個問題?我唯一能想到的是 cookie 即將到期並在幕後重新發布,但我不知道為什麼(或是否)會發生這種情況。

是的,問題很可能是 cookie 過期了。由於您沒有將自定義聲明添加到數據庫中的使用者聲明中,因此它們會在刷新時失去,因為您沒有在被呼叫的方法中添加聲明。您可以通過以下方式添加聲明:

userManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, user.FirstName));

或者您可以將其移動到重新生成 cookie 時呼叫的方法中(預設情況下,它的 user.GenerateUserIdentityAsync)。

       app.UseCookieAuthentication(new CookieAuthenticationOptions {
           AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
           LoginPath = new PathString("/Account/Login"),
           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.FromMinutes(30),
                   regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
           }
       });

引用自:https://stackoverflow.com/questions/23622047