Accessing Active Directory username when using Certification Authentication

71 Views Asked by At

I'm converting an ASP.NET 4.5 project to ASP.NET Core 7 and having issues using with authentication.

It's hosted on Windows Server 2016 not using any Azure services.

In ASP.NET 4.5, I used HttpContext.Current.User and it would return the Active Directory username (ex. FIRST.LAST). In Core, I had to add CertificationAuthentication to the ASP.NET Core but I need to access the Active Directory username. I know the certificate is connected to the users Active Directory account but I can't figure out how to access it. The recommendation is to use User.Identity.Name in Core but it's returning the Certificate name (ex. LAST.FIRST.123456789).

In ASP.NET 4.5 I didn't have to do anything special with the certificate. IIS prompted for the Cert and my app was Windows authenticated automagically. We used VB.NET and Me.User in a page returned the Active Directory username.

Everything I try returns the Certificate info. Any help to steer me in the right now would be helpful.

1

There are 1 best solutions below

0
On

It could be configured, you could check this document

builder.Services.AddAuthentication(
        CertificateAuthenticationDefaults.AuthenticationScheme)
    .AddCertificate(options =>
    {
        options.Events = new CertificateAuthenticationEvents
        {
            OnCertificateValidated = context =>
            {
                var claims = new[]
                {
                    
                    new Claim(
                        ClaimTypes.Name,
                        context.ClientCertificate.Subject // modify it yourself,
                        ClaimValueTypes.String, context.Options.ClaimsIssuer)
                };

                context.Principal = new ClaimsPrincipal(
                    new ClaimsIdentity(claims, context.Scheme.Name));
                context.Success();

                return Task.CompletedTask;
            }
        };
    });