How to add claims in ASP.NET Identity
Solution 1:
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;
Solution 2:
Perhaps the following article can help:
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "Brock"));
claims.Add(new Claim(ClaimTypes.Email, "[email protected]"));
var id = new ClaimsIdentity(claims,DefaultAuthenticationTypes.ApplicationCookie);
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(id);