ASP.NET Core by Patrik

Adding claims to existing identity

Here’s my claims transformation that adds roles to user identity.

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;
    }
}
ASP.NET Core
Identity
Claims

Comments

Leave a Comment

All fields are required. Your email address will not be published.