Search code examples
c#authenticationasp.net-core-webapiclient-certificates

ASP.NET Core Web API : basic authentication + certificate mapping


I have an ASP.NET Core Web API that uses basic auth and SSL is required.

I have

services.AddAuthentication(o => {
                                    o.DefaultScheme = IISDefaults.AuthenticationScheme;
                                });

and in every controller [Authorize].

I need to add an option so client just sends certificate and map it in to user. So I added

services.AddAuthentication(
             o => {
                      o.DefaultScheme = IISDefaults.AuthenticationScheme;
                  })
        .AddCertificate().

And in IIS, I added client cert mapping auth so it map client cert to Windows user testuser, and it does work correctly.

Because in inetpub/logs/, I see

2024-04-10 12:25:38 ::1 POST /sp/TestParams - 5264 testuser ::1 PostmanRuntime/7.29.2 - 401 0 0 383

so it is being mapped to 'testuser'.

But why am I getting an error:

HTTP 401 - unauthorized

What I need to add so it works as I want. Does this cert mapping work as I was thinking - that for the app it is = basic / Windows auth overall ?

I need this 'mapped' username in app later from HttpContextAccessor also.

Please advise.

Thanks and regards


Solution

  • ok so for future searchers...

    there is no way to have both finaly i added some flag in appsettings.json

    if (a.UseCertMapingAuth)
     {
         services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme).AddCertificate(
             o => 
             {
                 o.RevocationMode = System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck; 
             });
     }
     else
     {
         services.AddAuthentication(
             o =>
             {
                 o.DefaultScheme = IISDefaults.AuthenticationScheme;
             });
     }
    

    and im hosting 2 projects on 2 sites one with basic +cert and second with cert only