Updating Existing Claims in .NET with Cookie Authentication

If you are using cookie based authentication in your .NET application and setting claims, updating those claims can be a real pain. This post has some simple code to make this happen.

First of all, let’s set the scenario. If we are not changing security based settings, and for example just updating someone’s name, or maybe a profile picture, then we need a simple way of doing this.

Let’s take a look at some code.

var claims = User.Claims.ToList();
var claim = claims.FirstOrDefault(x => x.Type == "Photo");
if (claim != null)
{
    claims.Remove(claim);
    claims.Add(new Claim("Photo", string.Empty));

    var appIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    var user = new ClaimsPrincipal(appIdentity);
                
    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);
}

Let’s now run through this step by step.

Analyse the code

The first step is to retrieve a list of all current claims, we do this so that we have an existing list of what was already set, then we don’t loose anything that we’ve already got set. This is done with the following line: var claims = User.Claims.ToList();

Next, we can look for the specific claim we want to update, in this example, I’m using a user’s profile photo. Here it is: var claim = claims.FirstOrDefault(x => x.Type == "Photo");

Then we have a simple null check to ensure we can continue. We then remove the claim using claims.Remove(claim);. From here we can then add it back in with the new value, whatever that might be.

Finally, we setup a new claims identity, it’s important to make sure you add the parameter CookieAuthenticationDefaults.AuthenticationScheme, otherwise you will get a runtime error, this requirement was added in .NET Core 3.

Then assign the user a new ClaimsPrincipal, against the identity you just created, then call signin again as follows: await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);.

Then a callback to refresh the page, or whatever action you want means that you have updated the property, without the need for complex event hooks into the identity platform.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.