Irshu Irshu - 10 days ago 13
C# Question

How to update a claim in ASP.NET Identity?

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

SignInAsync


private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
var AccountNo = "101";
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
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
AccountNo
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
{

get
{
var CP = ClaimsPrincipal.Current.Identities.First();
var Account= CP.Claims.FirstOrDefault(p => p.Type == ClaimTypes.UserData);
return Account.Value;
}
set
{
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
'http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata:
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
RolePrincipal.


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

Answer

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

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


        }
Comments