20

I am storing custom claims, such as the user's real name, in the ASP.NET Identity cookie to avoid unnecessary database queries on every request. At least that's what I assume this code is doing:

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

This works fine, and I can retrieve these claims with:

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;
}

The identity.Claims property contains the following claims, as expected:

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: [email protected]
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

The trouble is that after some time (usually several hours), my custom claims seem to disappear - in this example, givenname no longer exists in the enumeration. The user is still authenticated, and all the default claims are still there.

What's going on, and how can I fix this? The only thing I can think of is that the cookie is expiring and being re-issued behind the scenes, but I don't know why (or if) that would happen.

5
  • Hi @James. Can I ask a question. You said you were doing this to "avoid unnecessary database queries on every request". That made me think that Identity must access the database on every request. Is that true? I did a very simple test and it didn't seem to access the database (based on there being no output from DbContext.Database.Log), but maybe it was cached. Would be nice to know as a per HTTP request database access would be bad news. Nov 18, 2014 at 12:25
  • @JonSmith If I didn't cache the user's real name somewhere (i.e. in the auth cookie), I'd need to query the Customers table every time I want to know what their name is.
    – James
    Nov 18, 2014 at 20:12
  • Hi @James. OK, I get that now. I had almost the same issue but by adding it as a claim in the database it automatically appeared in the cookie. I assume the cookie must be carrying all the User's information, which is how it sets up the IPrincipal without needing a lookup. Nov 19, 2014 at 8:21
  • I am having similar situation, using session based cookies, after several hours, even though my session is active and user is authenticated but the username no longer exists.
    – PAR
    Feb 26, 2022 at 1:11
  • Check out this answer for .NET 6: stackoverflow.com/a/76790172/8644294
    – Ash K
    Jul 28 at 18:17

2 Answers 2

19

Yes, the issue is most likely the cookie getting expired. Since you didn't add the custom claims to the user's claims in the database, they are lost on refresh since you aren't adding the claim inside the method being called. You can either add the claim via:

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

or you can move this inside of the method that's called when the cookie is regenerated (by default its 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))
            }
        });
3
  • 1
    Many thanks for your advice. I'd rather not persist claims to the database, because then the user's first name would be stored twice (in the Users and Claims tables) and I'd need to worry about keeping both up to date. Please could you elaborate on the GenerateUserIdentityAsync method? Where do I need to include the snippet you have provided, and where do I add the GivenName claim? Thanks again.
    – James
    May 13, 2014 at 19:47
  • 3
    You already have a GenerateUserIdentity method which is called in your sign in. You should just move the code where you add the claim into that method, and you should be good
    – Hao Kung
    May 13, 2014 at 22:03
  • i have similar requirements, but my user name (and other app information) is actually stored in a separate database (not the identity db), so at login, when the GenerateUserIdentityAsync() method is invoked, I need to query my other EF dbcontext to retrieve that data, and add the custom claims to the identity, correct? Dec 3, 2014 at 18:57
1

In Net5 you can get old cookie Custom Claim and add to new cookie like this,

builder.Services.Configure<SecurityStampValidatorOptions>(options =>
{
    // set time how oftern the cookie is invalidated
    options.ValidationInterval = TimeSpan.FromMinutes(10);

    options.OnRefreshingPrincipal = context =>
    {
        // Get my custom claim from old cookie
        var guidClaim = context.CurrentPrincipal.FindFirst("GUID");

        // Add value to new cookie
        if (guidClaim != null)
            context.NewPrincipal.Identities.First().AddClaim(guidClaim);

        return Task.FromResult(0);
    };
});
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.