Irshu Irshu - 10 months ago 165
C# Question

How to update a claim in ASP.NET Identity?

I'm using OWIN authentication for my MVC5 project.
This is my


private async Task SignInAsync(ApplicationUser user, bool isPersistent)
var AccountNo = "101";
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim(ClaimTypes.UserData, AccountNo));
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent, RedirectUri="Account/Index"}, identity);

As you can see, i added
into the Claims list.

Now, how can I update this Claim at some point in my application? So far, i have this:

public string AccountNo

var CP = ClaimsPrincipal.Current.Identities.First();
var Account= CP.Claims.FirstOrDefault(p => p.Type == ClaimTypes.UserData);
return Account.Value;
var CP = ClaimsPrincipal.Current.Identities.First();
var AccountNo= CP.Claims.FirstOrDefault(p => p.Type == ClaimTypes.UserData).Value;
CP.RemoveClaim(new Claim(ClaimTypes.UserData,AccountNo));
CP.AddClaim(new Claim(ClaimTypes.UserData, value));


when i try to remove the claim, I get this exception:

The Claim
101' was not able to be removed. It is either not part of this
Identity or it is a claim that is owned by the Principal that contains
this Identity. For example, the Principal will own the claim when
creating a GenericPrincipal with roles. The roles will be exposed
through the Identity that is passed in the constructor, but not
actually owned by the Identity. Similar logic exists for a

Could someone help me figure out how to update the Claim?

Answer Source

Turns out,you can create a new ClaimsIdentity and then do the claims updation.

            var AuthenticationManager = HttpContext.GetOwinContext().Authentication;
            var Identity = new ClaimsIdentity(User.Identity);
            Identity.AddClaim(new Claim("AccountNo", value));
            AuthenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant
(new ClaimsPrincipal(Identity), new AuthenticationProperties { IsPersistent = true });