'.net WebAPI webapp: How to support Client Certificate Authentication and Microsoft Identity Authentication with either-or?
We have a WebAPI webapp which should support authentication via client certificate and authentication via Microsoft Identity/OAuth2. With our current implementation, it seems that the Microsoft Identity Authentication overrules the Client Certificate Authentication. If we just add the Microsoft Identity Authentication in first place, then the overruling behaves the opposite round.
The Program.cs for authentication looks currently like this:
var builder = WebApplication.CreateBuilder(args);
// 1. setup Certificate Authentication
builder.Services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme).AddCertificate(options =>
{
// https://docs.microsoft.com/en-us/aspnet/core/security/authentication/certauth
options.AllowedCertificateTypes = CertificateTypes.All;
options.Events = new CertificateAuthenticationEvents
{
OnCertificateValidated = context =>
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, context.ClientCertificate.Subject, ClaimValueTypes.String, context.Options.ClaimsIssuer),
new Claim(ClaimTypes.Name, context.ClientCertificate.Subject, ClaimValueTypes.String, context.Options.ClaimsIssuer),
// since with that authentication we have no retrieved authorization from anywhere, we set it explicitly - for now ...
new Claim("scp", "GeneralScope")
};
context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
context.Success();
return Task.CompletedTask;
},
OnChallenge = x =>
{
return Task.CompletedTask;
}
};
});
builder.WebHost.ConfigureKestrel(options =>
{
options.ConfigureHttpsDefaults(opts =>
{
opts.ClientCertificateMode = ClientCertificateMode.AllowCertificate;
opts.ClientCertificateValidation = (cert, chain, policyErrors) =>
{
// TODO validate certificate
return true;
};
});
});
// 2. setup Microsoft Identity Authentication
var jwtAuthentication = builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme);
jwtAuthentication.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
jwtAuthentication.AddAppServicesAuthentication();
....
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Dont be confused about the sloppy client certificate validation, this is still work in progress.
How do we need to change the code so we can have the two authentication modes along each other with a either-or way?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
