Overriding ASP.NET Core Windows Authentication Identity

336 Views Asked by At

I was looking to use Windows Authentication for a Blazor Server app, but hit a small issue with the default Identity Name. i.e. when you used

<AuthorizeView>
   Hi @context.User.Identity.Name
</AuthorizeView>

I got back 'Hi DOMAIN\A123456', which might be the AD object name, but its not what users would say their name was. I also noticed during debugging that the Identity had pulled back all of my AD groups, but not things like Given Name.

How can I override/amend/alter the processing to 'fix' this, ideally put a proper name in the Name claim and move the id into the NameIdentifier claim.

1

There are 1 best solutions below

0
cjb110 On

This is what I came up with using IClaimsTransformation, but not sure if its the right approach at all, esp given that with just the out-of-the-box Blazor project this thing is called 7 times! If I added any db type logic to get the roles or name then this is going tank performance...

public class RoleClaimsTransformer : IClaimsTransformation
{
    private readonly ILogger<RoleClaimsTransformer> _logger;

    public RoleClaimsTransformer(ILogger<RoleClaimsTransformer> logger)
    {
        _logger = logger;
    }

    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        _logger.LogDebug($"Role Transform for {principal.Identity.Name} Auth: {principal.Identity.IsAuthenticated}");

        //get the original name claim
        var ci = (ClaimsIdentity)principal.Identity;
        Claim nameClaim = principal.FindFirst(ci.NameClaimType);

        //create a new principal
        ClaimsPrincipal newCP = new ClaimsPrincipal();
        //and a new identity, using the original authtype (just in case it matters down the line)
        var newId = new GenericIdentity("Joe Bloggs", principal.Identity.AuthenticationType);
        //add the original name as a NameId
        newId.AddClaim(new Claim(ClaimTypes.NameIdentifier, nameClaim.Value));
        //add roles etc
        newId.AddClaim(new Claim(ClaimTypes.Role, "admin"));

        newCP.AddIdentity(newId);

        return Task.FromResult(newCP);
    }
}

Hopefully its reasonably clear what I've done, but basically ignore the principal from the built in Windows Auth and create your own. Also note that the GenericIdentity does want a ClaimTypes.Role for roles (for use in the AuthorizeView components), and not whatever type the WindowsIdentity needed.

I've subsequently realised that WindowsAuthentication isn't not going to work for my app, and I'll go back to custom auth that just uses AD to check their passwords via a standard pair of login boxes.