I am developing a MVC 5 internet application and am using Identity 2.1
.
How can I add a claim
to a user, after the user has logged in, where I knows the username
?
Here is what I have:
public void AddClaimToUser(string userName, string type, string value )
{
var AuthenticationManager = HttpContext.Current.GetOwinContext().Authentication;
var Identity = new ClaimsIdentity(userName);
Identity.AddClaim(new Claim(type, value));
AuthenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(Identity), new AuthenticationProperties { IsPersistent = true });
}
However, after I call this method, and I check the claims for the user, the added claim
is not listed.
Here is the code that I am using to get the claims in a controller:
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
Thanks in advance.
First Of all you have to create a method for add claim under IdentityModels.cs class.like this,in below code i have created a claim for CompanyId.
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsActive { get; set; }
public int? CompanyId { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
userIdentity.AddClaim(new Claim("CompanyId", (this.CompanyId + "" ?? "0")));
return userIdentity;
}}
After write above code,you need to write one more method in IdentityConfig.cs
public static class IdentityExtensions{
public static int CompanyId(this IIdentity identity)
{
return Convert.ToInt32(((ClaimsIdentity)identity).FindFirst("CompanyId").Value);
}}
After this you can get your created claim in any controller by just typing..
int companyId = User.Identity.CompanyId();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With