Using Claims in ASP.NET Identity

Claims can simplify and increase the performance of authentication and authorization processes. I wrote about how you can use the roles stored as claims to eliminate back-end queries every time authorization takes place.  ASP.NET Identity has good support for claims-based identity and it creates several claims for you automatically when you create a new identity.  Here is how we create the identity for a new user during the log-in process

UserManager<applicationuser> userManager = new UserManager<applicationuser>(new UserStore<applicationuser>(new SecurityContext()));
ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

If you inspect the Claims property of ClaimsIdentity after calling CreateIdentity you will see that there are there are three or more claims. There is a claim for the user ID, user name, identity provider and one for each role assigned. So what if you want to add some more claims? Here is an example of how to add the email as a claim.

var user = userManager.Find(userName, password);
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));

ClaimTypes is an object that contains constant strings that represent the claim type. These are usually in the format of a URI. For example the Email type is "". If you want to add a claim that is not represented in the ClaimTypes object then you can use your own string to represent the type. I usually create a static object of my own to store any custom types. You will need to know what that constant string is when you query for the claim. Here is how we get the email claim from an identity.

var prinicpal = (ClaimsPrincipal)Thread.CurrentPrincipal;
var email = prinicpal.Claims.Where(c => c.Type == ClaimTypes.Email).Select(c => c.Value).SingleOrDefault();

So how was the custom email claim saved in the CurrentPrincipal and persisted in the cookie? It is when we call the SignIn method to complete the log-in process, passing in the identity we created with the custom claim added.

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = persistCookie }, identity);

Using claims-based identity is very easy in ASP.NET Identity. But don't get carried away shoving everything about the user in as a claim. I would only keep it to items needed for authorization or that are accessed often in the application for the current user. How would you use claims-based identity in your applications?

Popular posts from this blog

Adding Email Confirmation to ASP.NET Identity in MVC 5

Customizing ASP.NET Identity in MVC 5