Can we have both OAuth and Certificate authentication in ASP .NET Core 5?

674 Views Asked by At

Currently, we have a working OAuth authentication for our ASP.NET Core 5 Web API. We would like to add a certificate authentication as well to be double sure of our caller. Is there a way to have both of them? I tried the below code but it overrides one over the other.

services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
.AddAzureADBearer(options =>
{
   options.Instance = aADInstance;
   options.ClientId = clientIdWithScope;
   options.Domain = aADDomain;
   options.TenantId = aADTenantId;
}
)
services.AddAuthentication(
CertificateAuthenticationDefaults.AuthenticationScheme)
        .AddCertificate(); 
1

There are 1 best solutions below

0
Gordon Khanh Ng. On

Changing default policy

// Add authentication schemes before, we already did this, so I would skip this part

// Change default Authorization policy
services.AddAuthorization(cfg =>
    cfg.DefaultPolicy =
        new AuthorizationPolicyBuilder(CertificateAuthenticationDefaults.AuthenticationScheme,
            AzureADDefaults.JwtBearerAuthenticationScheme).RequireAuthenticatedUser().Build());

[Authorize] attribute now would require all http request to satisfied both CertificateAuthenticationDefaults.AuthenticationScheme and AzureADDefaults.JwtBearerAuthenticationScheme, that might be not the behavior we want for all of our endpoint, so, be careful with this approach.

Add our own policy

// Add authentication schemes before, we already did this, so I would skip this part

// Adding our own policy
services.AddAuthorization(options =>
{
    options.AddPolicy("ComposedPolicy", p =>
    {
        p.AuthenticationSchemes = new List<string>
            {CertificateAuthenticationDefaults.AuthenticationScheme, AzureADDefaults.JwtBearerAuthenticationScheme};
        p.RequireAuthenticatedUser();
        p.Build();
    });
});

[Authorize] attribute behavior now would be untouch, but whenever we want to use our custom policy, we must specify them by [Authorize(Policy = "ComposedPolicy")].

Just choose the approach that suit the best.