Using Windows Authentication in an ASP.NET Core 2.1 application. In the database we have a User table that stores users along with their Sid. It has a 1-1 relationship with UserProfile which has information I want to use for Claims.
I added a this service for Claims Transformation:
public class UserStatusClaimsTransformation : IClaimsTransformation { private readonly MyDbContext _context; public UserStatusClaimsTransformation(MyDbContext context) { _context = context; } public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal) { if (principal.Identity is WindowsIdentity identity) { User user = await _context.User .Include(u => u.UserProfile) .Where(u => new SecurityIdentifier(u.WindowsSid, 0) == identity.User) .SingleOrDefaultAsync(); if (user != null) { identity.AddClaim(new Claim("Status", user.UserProfile)); } } return principal; } } My issue is, once this service is registered, the IPrincipal accessed elsewhere in the pipeline is now a ClaimsPrincipal instead of a WindowsPrincipal. Example, in MyDbContext I inject IPrincipal via DI:
public MyDbContext(DbContextOptions<MyDbContext> options, IPrincipal principal) : base(options) { _principal = principal; } Previously, this was a WindowsPrincipal and I could get the Username from _principal.Identity.Name, but after registering my Claims Transformer it is a ClaimsPrincipal and _principal.Identity.Name is null. Is there a way to keep the IPrincipal provided through DI as a WindowsPrincipal after using the Claims Transformation?