Adding claims to existing identity

During moving one system from classic ASP.NET MVC to ASP.NET Core I faced an interesting challenge. Although access to system is based on Active Directory there is separate role management based on classic membership and roles providers. There are reasons why AD is not used for role management and I cannot change it. ASP.NET Core uses claims-based authentication and I needed to find a way to add role claims to authenticated identity. Here’s  the solution.

How things does not work

Adding claims to existing identity seems like small task to accomplish. But, well, it doesn’t go so easy. We can build middleware class and try something like shown here.

foreach(var role in user.Roles)
{
    var claim = new Claim(newIdentity.RoleClaimType, role.Name);
    identity.AddClaim(claim);
}

But it doesn’t work with existing identity. No errors, code runs smooth but role claims are just ignored.

Using claims transformation

There’s correct way to edit existing identity and it’s called claims transformation. Basically we have to write a custom class that implements IClaimsTransformation interface. Documentation doesn’t give much information about it but most important thing is said – we need to clone given identity.

In short, here’s how the process goes:

  1. Clone current user identity
  2. Add custom claims
  3. Return cloned identity

Here’s my claims transformation that adds roles to user identity. Notice that I can use dependency injection to inject instances of service classes to my claims transformation. Remember important trick – we need a clone of current identity to make things work.

public class AddRolesClaimsTransformation : IClaimsTransformation
{
    private readonly IUserService _userService;

    public AddRolesClaimsTransformation(IUserService userService)
    {
        _userService = userService;
    }

    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        // Clone current identity
        var clone = principal.Clone();
        var newIdentity = (ClaimsIdentity)clone.Identity;

        // Support AD and local accounts
        var nameId = principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier ||
                                                          c.Type == ClaimTypes.Name);
        if (nameId == null)
        {
            return principal;
        }

        // Get user from database
        var user = await _userService.GetByUserName(nameId.Value);
        if (user == null)
        {
            return principal;
        }

        // Add role claims to cloned identity
        foreach(var role in user.Roles)
        {
            var claim = new Claim(newIdentity.RoleClaimType, role.Name);
            newIdentity.AddClaim(claim);
        }

        return clone;
    }
}

The final thing to do is to register claims transformation with dependency injection in ConfigureServices() method of Startup class.

services.AddScoped<IClaimsTransformation, AddRolesClaimsTransformation>();

Considering you have authentication already configured and it works, the registered transform will get to authentication flow.

Wrapping up

Although adding few claims to existing identity seems like piece of cake, it is not so easy. We cannot just add claims to existing identity and hack it. Claims transformation as custom implementation of IClaimsTransformation interface is the tool we need to use to add claims to existing identity. As we saw we don’t modify existing identity but we clone it, add claims and then return the cloned instance.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    17 thoughts on “Adding claims to existing identity

    • November 24, 2020 at 9:30 am
      Permalink

      I am so glad that you wrote this post.

    • November 26, 2020 at 6:41 pm
      Permalink

      Thank you, thank you, thank you. Been looking for this forever. Does this work with Blazor wasm as well?

    • November 26, 2020 at 8:27 pm
      Permalink

      I have made no experiments on Blazor yet. I needed this solution just for regular ASP.NET Core application.

    • February 10, 2021 at 10:37 am
      Permalink

      When does this run in the request pipeline?

      I’ve done this using middleware with great success but this indeed this seems like the standard approach.

    • March 11, 2021 at 11:13 am
      Permalink

      does not work, it also returns a 500 but no exception whatsoever, which makes it hard to figure what’s going on

      also, what if one need a db injection, to check the user role ?

    • April 2, 2021 at 3:21 pm
      Permalink

      I find that TransformAsync gets called every time a page is loaded, and the principal does not have any of the claims that I added on the previous page load, which means that I have to add them again. This means I have to call the database every time to get the user information that I use to create the claims.

      Is this normal? Is there a way to persist the claims between pages? Using .Net Core 3.1 and Windows auth.

    • June 5, 2021 at 6:16 pm
      Permalink

      This was a very helpful article. I used this technique with a Blazor server and it’s working great. I noticed when debugging that the transformation is called multiple times during the login process, so the user service gets called multiple times too. It’s not a big deal.

      I was thinking that maybe the principal argument to TransformAsync would be the transformed version on the repeated calls but it’s not. The original principle is passed in on each call so I can’t really “mark” it to know I’ve already done the transformation. I will setup the UserService so that caches the data on the first call then the repeated calls to TransformAsync won’t require a database call every time.

    • August 1, 2021 at 1:33 am
      Permalink

      Thank you so much for this post

    • September 13, 2021 at 11:48 am
      Permalink

      Well I have the same issue as Adrian and Matthew. I’m also doing a call during transformation to get the user. I’m doing this in order to add the correct claims. I would like to persist the claims or persist the result from the user API call.

    • November 11, 2021 at 8:07 am
      Permalink

      This is good, but I prefer this approach – https://stackoverflow.com/a/52173219/540156

      Taken from the PolicyServer source code.
      You add a second identity which can be differentiated by Authtype property of ClaimsIdentity.

      Works really nicely and general calls like HasClaim checks both identities.

    • December 22, 2021 at 9:58 pm
      Permalink

      This was very helpful to me. I’m working on a codebase that used to use a bearer token instead of a cookie and I really didn’t want to change more than I had to. This post gave me a pretty simple way to implement the same Claims modifications that were being done previously, but weren’t available when not modifying the underlying identity information.

    • February 5, 2022 at 12:36 am
      Permalink

      Great post!!
      Basically main point is to clone principal. It can be done on several places like in claimstransformation, middleware…. I clone it on jwtbearer event OnTokenValidated

    • June 29, 2022 at 12:57 pm
      Permalink

      Thanks for the post! Does this work with Azure AD B2C?

    • August 13, 2022 at 4:02 pm
      Permalink

      Thanks for the post, but how can I persist this so I don’t have to call DB all the time to get additional information ?
      I would like to set some custom claims when user logs in and persist them until the user logs out ?

    • January 6, 2023 at 7:41 pm
      Permalink

      Thanks for the informative blog. I have one question when TransformAsync is getting called twice. When making get request also its duplicating the claims.

    • February 14, 2023 at 12:28 am
      Permalink

      Working great. This is what I have been looking around.
      However as others also asked, every request is making a DB call to get the user roles and and adding the claims. Once a user is authenticated and claims are added, they should be part of the coockie and this routine should not be repeated as long as coockie is not expired.
      Could not find help on that yet.

    • June 6, 2023 at 12:35 pm
      Permalink

      As Prasad suggest this is not ideal. Every request runs this code. It’s worse than the problem I am trying to solve which is to store some additional user information from another table when the user logs in and then clear it when they log out.

    Leave a Reply

    Your email address will not be published. Required fields are marked *