In this article, I would share a .NET 6.0 Web API sample code that supports Client certificate authentication.
The sample code
utilizes the build-in feature of .NET
Microsoft.AspNetCore.Authentication.Certificate
that is SIMILAR to Certificate Request of Handshake Protocol written in The Transport Layer Security Protocol (RFC5246).
Web Server requires a client certificate and validate the certificate is trusted during TLS handshake.
CertificateAuthenticationOptions
handler checks the certificate type.
CertificateValidationService
validates the pfx file or thumbprint.
Controller has to have
[Authorize]
attribute because it deals with the context determined in TLS handshake and Authentication/Authorization middleware.
Configure Kestrel server for a local run so it requires a client certificate during TLS handshake
Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode
has options such as
RequireCertificate
and
AllowCertificate
. Once you set
RequireCertificate
, any request without a client certificate is declined.
A self-signed certificate does not work without
AllowAnyClientCertificate()
method.
An event handler CertificateAuthenticationEvents is triggered during a TLS handshake, which is written with builder.Services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme) in Program.cs.
A self-signed certificate requires CertificateAuthenticationOptions.AllowedCertificateTypes property to be All or SelfSigned.
The CertificateAuthenticationOptions handler calls CertificateValidationService and set the context success or fail.
If the validation fails, it returns 403 forbidden during the TLS handshake before it reaches .NET application.
builder.Services.AddAuthentication(
CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate(options =>
options.AllowedCertificateTypes = CertificateTypes.All;
options.Events = new CertificateAuthenticationEvents
OnCertificateValidated = context =>
var validationService = context.HttpContext.RequestServices
.GetRequiredService<ICertificateValidationService>();
if (validationService.ValidateCertificate(context.ClientCertificate))
context.Success();
context.Fail("Invalid certificate");
return Task.CompletedTask;
Enter fullscreen modeExit fullscreen modeCertificateValidationService handles the certificate validation and returns true/false to CertificateAuthenticationOptions handler.
To validate an incoming client certificate, the Web API app config has Pfx file path and Pfx password, or the certificate thumbprint.
If the Web API instance does not have the Pfx file, for example, if it is deployed in Azure App Service, the service validates if the incoming certificate thumbprint is identical with the one in the app config.