Simon
Simon

Reputation: 8357

MVC 5 - Add a claim to a user

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.

Upvotes: 9

Views: 5920

Answers (2)

Ankur Vaish
Ankur Vaish

Reputation: 31

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();

Upvotes: 3

trailmax
trailmax

Reputation: 35106

Giving AuthenticationResponseGrant is not enough to add claim to already logged in user. You need to get identity, add new claim ( you already do this), then sign user out and sign-in again. I pretty much do this in this answer

Upvotes: 0

Related Questions