Search code examples
asp.netasp.net-mvcasp.net-mvc-5asp.net-identityasp.net-web-api2

Is there any benefit to storing user information in AspNetUserClaims with Asp.Net Identity 2?


I would like to store some additional user information. From what I understand the following is the usual option:

public class ApplicationUser : IdentityUser {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
        public string FirstName { get; set; }
        public string LastName { get; set; }

    }

Here the FirstName and LastName have been added and they will appear as additional fields in the AspNetUsers table.

However it seems that now with Asp.Net Identity there's also an option to store this type of information in the AspNetUserClaims table.

Can someone explain to me. Going forward is this the kind of information that could be stored in AspNetUserClaims. If so then does anyone have any examples of this.


Solution

  • At the end of the day, your signed in user will be converted into a series of claims stored in the ClaimsIdentity representing your user in HttpContext.User.Identity. You can choose to store FirstName/LastName as columns in the user table which you then can explicitly read out and convert into the appropriate claims (if desired), or you can store them directly as claims in the AspnetUserClaims table (which is just stores them as two string columns) which by default will just automatically get added to your user's claims identity. Both methods are more or less equivalent though, so its up to personal preference.

    BTW the only reason you would want these in the user's ClaimsIdentity at all, is if you wanted to save a db hit just to display the name, and always use the FirstName/LastName claims in the ClaimsIdentity. If you fetch the user, and use user.FirstName instead, there isn't much value in also generating the name claims.