身份cookie在一段时间后丢失自定义声明信息

Jam*_*mes 15 asp.net cookies asp.net-identity

我将自定义声明(例如用户的真实姓名)存储在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);
Run Code Online (Sandbox Code Playgroud)

这很好用,我可以用以下方法检索这些声明:

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;
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

问题是,经过一段时间(通常是几个小时)后,我的自定义声明似乎消失了 - 在此示例中,givenname枚举中不再存在.用户仍然经过身份验证,并且所有默认声明仍然存在.

发生了什么,我该如何解决这个问题?我唯一能想到的是cookie即将到期并在幕后重新发布,但我不知道为什么(或者如果)会发生.

Hao*_*ung 18

是的,问题很可能是cookie过期了.由于您没有在数据库中将自定义声明添加到用户的声明中,因此您不会在刷新时丢失它们,因为您没有在被调用的方法中添加声明.您可以通过以下方式添加声明:

userManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, user.FirstName));
Run Code Online (Sandbox Code Playgroud)

或者您可以在重新生成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))
            }
        });
Run Code Online (Sandbox Code Playgroud)

  • 您已经拥有了一个GenerateUserIdentity方法,该方法在您的登录中被调用.您应该只将代码添加到该方法中,并且您应该是好的 (3认同)