asp.net – 身份cookie在一段时间后会丢失自定义索赔信息

前端之家收集整理的这篇文章主要介绍了asp.net – 身份cookie在一段时间后会丢失自定义索赔信息前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在ASP.NET Identity cookie中存储自定义声明,例如用户的真实姓名,以避免在每个请求上进行不必要的数据库查询.至少这是我认为这个代码正在做的:
  1. var identity = await user.GenerateUserIdentityAsync(UserManager);
  2. identity.AddClaim(new Claim(ClaimTypes.GivenName,user.FirstName)));
  3. // etc.
  4. AuthenticationManager.SignIn(new AuthenticationProperties {IsPersistent=true},identity);

这工作正常,我可以通过以下方式检索这些声明:

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

identity.Claims属性包含以下声明,如预期的:

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

麻烦的是,经过一段时间(通常是几个小时),我的自定义声明似乎消失了 – 在这个例子中,给定名称不再存在于枚举中.用户仍然通过身份验证,所有默认声明仍然存在.

发生了什么,怎么解决这个问题?我唯一可以想到的是,cookie正在过期,并在幕后重新发布,但我不知道为什么(或如果)会发生.

解决方法

是的,这个问题很可能是cookie过期了.由于您没有将自定义声明添加数据库中的用户声明中,所以它们在刷新时丢失,因为您不会在调用方法添加声明.您可以通过以下方式添加声明:
  1. userManager.AddClaim(user.Id,new Claim(ClaimTypes.GivenName,user.FirstName));

或者您可以在重新生成cookie时调用方法(默认情况下为user.GenerateUserIdentityAsync)将其移动.

  1. app.UseCookieAuthentication(new CookieAuthenticationOptions {
  2. AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,LoginPath = new PathString("/Account/Login"),Provider = new CookieAuthenticationProvider {
  3. // Enables the application to validate the security stamp when the user logs in.
  4. // This is a security feature which is used when you change a password or add an external login to your account.
  5. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager,ApplicationUser>(
  6. validateInterval: TimeSpan.FromMinutes(30),regenerateIdentity: (manager,user) => user.GenerateUserIdentityAsync(manager))
  7. }
  8. });

猜你在找的asp.Net相关文章