Update a value stored in Claims(System.Security.Claims)

I have applied the authentication using the claims based indentity

  var identity = new ClaimsIdentity(new[] {
                                new Claim(ClaimTypes.Name, userContext.ReturnObject.UserName),
                                new Claim(ClaimTypes.Email, userContext.ReturnObject.EmailAddress)
                            }, "ApplicationCookie");

Now i am trying to update the username stored in claims.

I can read the values using

var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;

but i am not able to update. please suggest.

Upvotes: 0

Views: 3332

Answers (3)

Luis Teijon
Luis Teijon

Reputation: 4899

After doing what @Andy and @Mukesh said, you will also need to change the authentication cookies after updating claims in order the changes to take effect.

IOwinContext context = Request.GetOwinContext();

var authenticationContext = context.Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(
            identity,
            authenticationContext.Properties);

Further information can be found here

Upvotes: 0

Mukesh Modhvadiya
Mukesh Modhvadiya

Reputation: 2178

I don't understand why you want to update the claim, but you may try something like this as said by Andy

((ClaimsIdentity)identity).RemoveClaim(identity.FindFirst(ClaimTypes.Name)); 
((ClaimsIdentity)identity).AddClaim(new Claim(ClaimTypes.Name, "new_name"));

Upvotes: 1

Andy Hopper
Andy Hopper

Reputation: 3678

Claims weren't designed to be updated; they're intended to be atomic facts about the identity. However, the ClaimsIdentity class DOES have the ability to replace claims; you'll need to first find the claim you want to replace, then remove the claim from the ClaimsIdentity using RemoveClaim, followed by adding a replacement claim with the same claim type using AddClaim.

Upvotes: 0

Related Questions