Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add claims in ASP.NET Identity

I am trying to find a document or example of how you would add custom claims to the user identity in MVC 5 using ASP.NET Identity. The example should show where to insert the claims in the OWIN security pipeline and how to persist them in a cookie using forms authentication.

like image 279
Kevin Junghans Avatar asked Dec 04 '13 19:12

Kevin Junghans


People also ask

What are claims in asp net identity?

A claim is a name value pair that represents what the subject is, not what the subject can do. For example, you may have a driver's license, issued by a local driving license authority. Your driver's license has your date of birth on it.

What are claims in Identity Server?

Claims are pieces of information about a user that have been packaged, signed into security tokens and sent by an issuer or identity provider to relying party applications through a security token service (STS).


1 Answers

The correct place to add claims, assuming you are using the ASP.NET MVC 5 project template is in ApplicationUser.cs. Just search for Add custom user claims here. This will lead you to the GenerateUserIdentityAsync method. This is the method that is called when the ASP.NET Identity system has retrieved an ApplicationUser object and needs to turn that into a ClaimsIdentity. You will see this line of code:

// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 

After that is the comment:

// Add custom user claims here 

And finally, it returns the identity:

return userIdentity; 

So if you wanted to add a custom claim, your GenerateUserIdentityAsync might look something like:

// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);  // Add custom user claims here userIdentity.AddClaim(new Claim("myCustomClaim", "value of claim"));  return userIdentity; 
like image 90
dprothero Avatar answered Sep 18 '22 19:09

dprothero