Search code examples
c#asp.net-mvcentity-frameworkasp.net-mvc-5asp.net-identity

Understanding MVC5 UserClaim Table


I have been doing a lot of research but none resulted in helping me understand what is the point of UserClaim Table.

When you create a MVC5 project, there are some default tables created upon your database being registered. I understand the purpose of all of them except UserClaim.

From my understanding, User Claims are basically key pair values about the user. For example if I want to have a FavouriteBook field, I can add that field to the user table and access it. Actually I already have something like that built in. Each of my users have "Custom URL" And so I have created a claim in the following way:

public class User : IdentityUser
{
    public string CustomUrl { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        userIdentity.AddClaim(new Claim("CustomUrl", CustomUrl));
        return userIdentity;
    }
}

public static class UsersCustomUrl
{
    public static string GetCustomUrl(this IIdentity identity)
    {
        var claim = ((ClaimsIdentity)identity).FindFirst("CustomUrl");
        return (claim != null) ? claim.Value : string.Empty;
    }
}

Above basically allows me to access the CustomUrl by simply calling User.Identity.GetCustomUrl()

The above code won't write to the UserClaims table as the value exists in the Users Table. So what is the point of this table?

I am speculating that maybe I should add CustomUrl to UserClaims and somehow bind that to identity and that may what it is for? I would love to know the answer!


Solution

  • Claims are really useful in cases where you present multiple ways in which your users can register / sign on with your website... in particular, I'm talking about third-party authentication with organisations such as Google, Facebook and Twitter.

    After a user has authenticated themselves through their chosen third party, that third party will disclose a set of claims to you, a set of information that describes the user in a way that you can identify them.

    What information the claims will contain varies from provider to provider. For example, Google will share the users email address, their first name, their last name but compare that to Twitter... Twitter doesn't share any of that, you receive the identifier of their Twitter account along with their access tokens.

    Claims based authentication provides a simple method to facilitate all this information, whilst the alternative may very well have meant creating tables in your database for each individual provider you worked with.