Reputation: 514
I am making a ASP.NET MVC 5 application that uses Identity. Part of the authentication consists of storing a claim in a cookie, without saving it to a database, since that claim must only last until the user logs out. This claim is added to the user identity after log out, and the value of the claim can be changed by the user at any point while he is logged in. To do this I am using the following code:
var AuthenticationManager = HttpContext.GetOwinContext().Authentication;
var Identity = User.Identity as ClaimsIdentity;
if (Identity.HasClaim(c => c.Type == "custom"))
{
Identity.RemoveClaim(Identity.FindFirst("custom"));
}
Identity.AddClaim(new Claim("custom", "value", ClaimValueTypes.Integer32));
AuthenticationManager.AuthenticationResponseGrant =
new AuthenticationResponseGrant(new ClaimsPrincipal(Identity), new AuthenticationProperties { IsPersistent = true });
This works fine for a while... but about ten minutes after the user logs in the claim is gone! How can I make the claim persist until logout?
Upvotes: 1
Views: 1762
Reputation: 35116
Your problem is that SecurityStampValidator
that is configured in Startup.Auth.cs
is wiping away your custom claims that are stored in the cookie.
You need to look on this bit of code in ConfigureAuth(IAppBuilder app)
:
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(10),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
Especially function passed user.GenerateUserIdentityAsync(manager))
You need to modify this method ApplicationUser.GenerateUserIdentityAsync
to restore your custom claims there as well if they were present on the cookie.
Upvotes: 3