Introduction
Securing an API is an important part of building reliable backend applications. Most applications use authentication mechanisms such as JWT tokens, OAuth, or API keys to identify clients before allowing them to access protected resources. However, some systems require an additional level of security where the client application itself must prove its identity before establishing a trusted connection with the server.
Client certificate authentication provides this capability. It allows an API to verify a client's identity using a digital certificate during the HTTPS connection. This approach is commonly known as mutual TLS authentication, or mTLS, because both the client and server participate in certificate-based authentication.
For example, consider an ASP.NET Core API that communicates with payment gateways, internal enterprise applications, or services running inside a private network. Instead of relying only on an application-level token, the API can require trusted client certificates before accepting requests.
ASP.NET Core provides built-in certificate authentication support through the certificate authentication handler. Developers can use it to validate certificates, create authenticated identities, and apply authorization policies to protected endpoints.
In this article, we will explore how client certificate authentication works, how to configure it in ASP.NET Core, how to validate incoming certificates, and what developers should consider when using it in production environments.
What Is Client Certificate Authentication?
Client certificate authentication is a security mechanism in which a client presents a digital certificate to a server during an HTTPS connection.
A digital certificate contains information that helps establish the identity of its owner. It also contains a public key and is digitally signed by a certificate authority or another trusted issuer.
During a mutual TLS connection, the server requests a certificate from the client. The client presents its certificate, and the server validates it before allowing the connection to proceed.
A simplified authentication flow looks like this:
- The client sends an HTTPS request to the API.
- The server requests a client certificate during the TLS handshake.
- The client presents its certificate.
- The server validates the certificate chain, expiration, and trust requirements.
- The application creates an authenticated identity for the client.
- Authorization policies determine whether the client can access the requested endpoint.
This process helps ensure that only clients with acceptable certificates can establish authenticated connections.
It is important to understand that certificate authentication and JWT authentication solve different problems. A certificate establishes the identity of the connecting client, while a JWT usually represents an authenticated user or application identity at the application level. Depending on the security requirements, an application may use both mechanisms together.
Why Use Client Certificates in ASP.NET Core?
Client certificates are particularly useful when APIs communicate with trusted systems that need strong machine-to-machine authentication.
Consider an enterprise application where several internal services communicate with a central ASP.NET Core API. Each service has its own certificate issued by the organization's certificate authority.
The API can validate the presented certificate and identify which service is making the request.
This provides several benefits:
- Helps prevent unauthorized applications from connecting to protected APIs.
- Provides certificate-based machine identity.
- Supports mutual authentication over HTTPS.
- Reduces dependence on shared API keys.
- Works well for internal services and controlled enterprise integrations.
However, certificate authentication also introduces certificate issuance, renewal, expiration monitoring, and revocation management. These responsibilities should be considered before adopting it.
Configuring Client Certificate Authentication in ASP.NET Core
ASP.NET Core provides certificate authentication through the AspNetCore.Authentication.Certificate package.
First, install the required package:
dotnet add package Microsoft.AspNetCore.Authentication.CertificateThe package provides the certificate authentication handler and configuration options required to authenticate clients using X.509 certificates.
Register Certificate Authentication
Open Program.cs and configure certificate authentication.
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Authentication.Certificate;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddAuthentication(
CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate(options =>
{
options.AllowedCertificateTypes =
CertificateTypes.Chained;
options.RevocationMode =
X509RevocationMode.Online;
});
builder.Services.AddAuthorization();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();Let's understand the important configuration options.
AddAuthentication registers certificate authentication as an authentication scheme.
AllowedCertificateTypes specifies which certificate types are accepted. CertificateTypes.Chained requires certificates that can be validated through a trusted certificate chain.
RevocationMode determines how certificate revocation is checked. Online checking attempts to obtain current revocation information from the configured certificate infrastructure.
The middleware order is also important. UseAuthentication must execute before UseAuthorization because authorization depends on the authenticated identity established by the authentication middleware.
This configuration registers the authentication handler, but the HTTPS server must also be configured to request client certificates.
Configuring Kestrel to Request Client Certificates
Certificate authentication depends on the TLS handshake. Therefore, Kestrel must be configured to request or require a client certificate.
For example, configure HTTPS in Program.cs:
using Microsoft.AspNetCore.Server.Kestrel.Https;
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenAnyIP(5001, listenOptions =>
{
listenOptions.UseHttps(httpsOptions =>
{
httpsOptions.ClientCertificateMode =
ClientCertificateMode.RequireCertificate;
});
});
});ClientCertificateMode.RequireCertificate tells Kestrel to require a client certificate during the HTTPS handshake.
There are different certificate request modes:
| Mode | Behavior |
|---|---|
| NoCertificate | Does not request a client certificate |
| AllowCertificate | Requests a certificate but allows clients without one |
| RequireCertificate | Requires clients to provide a certificate |
For an API that must accept only certificate-authenticated clients, RequireCertificate is generally appropriate.
AllowCertificate can be useful when an application has both public and certificate-protected endpoints, but the application must explicitly enforce certificate authentication on the protected endpoints.
The HTTPS server certificate must also be configured correctly. The example assumes that the server's HTTPS certificate is already available through the application's hosting configuration.
Protecting API Endpoints With Certificate Authentication
After configuring authentication, the next step is protecting the API endpoints.
ASP.NET Core provides the Authorize attribute to require authentication.
Consider the following controller:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication.Certificate;
[ApiController]
[Route("api/services")]
public class ServiceController : ControllerBase
{
[HttpGet("status")]
[Authorize(
AuthenticationSchemes =
CertificateAuthenticationDefaults.AuthenticationScheme)]
public IActionResult GetStatus()
{
return Ok(new
{
Message = "Client certificate authentication successful",
Client = User.Identity?.Name
});
}
}The Authorize attribute ensures that the endpoint requires an authenticated identity created through the certificate authentication scheme.
If the client does not provide a valid certificate, the authentication process fails and access to the protected endpoint is denied.
This approach is useful when different controllers or endpoints have different authentication requirements.
Validating Client Certificates With Custom Logic
In production applications, validating the certificate chain is only one part of the authentication process.
An API may also need to verify whether the certificate belongs to an approved service, whether its subject or issuer matches organizational requirements, or whether it is registered in an application database.
ASP.NET Core provides certificate authentication events that allow developers to add custom validation logic.
For example:
builder.Services
.AddAuthentication(
CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate(options =>
{
options.AllowedCertificateTypes =
CertificateTypes.Chained;
options.Events = new CertificateAuthenticationEvents
{
OnCertificateValidated = context =>
{
var certificate = context.ClientCertificate;
if (certificate.NotAfter <= DateTime.UtcNow)
{
context.Fail("Certificate has expired.");
return Task.CompletedTask;
}
var claims = new[]
{
new System.Security.Claims.Claim(
System.Security.Claims.ClaimTypes.Name,
certificate.Subject
)
};
var identity =
new System.Security.Claims.ClaimsIdentity(
claims,
context.Scheme.Name
);
context.Principal =
new System.Security.Claims.ClaimsPrincipal(identity);
context.Success();
return Task.CompletedTask;
}
};
});The OnCertificateValidated event executes after the certificate authentication handler has performed its certificate validation.
The example creates a ClaimsPrincipal using the certificate subject.
In a real application, developers should validate the certificate against an explicit trust policy and identify clients using stable identifiers rather than relying only on the subject name. Certificate subjects can change when certificates are renewed.
For example, an application may maintain an approved certificate registry containing certificate thumbprints, public key identifiers, or other verified client identifiers.
A certificate should not be accepted simply because its subject contains an expected service name.
Calling the API With a Client Certificate
After configuring the API, the client application must present its certificate when establishing the HTTPS connection.
The following example demonstrates how to use HttpClient in a .NET application.
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
var certificate = new X509Certificate2(
"client-certificate.pfx",
"certificate-password",
X509KeyStorageFlags.EphemeralKeySet
);
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);
using var httpClient = new HttpClient(handler);
var response = await httpClient.GetAsync(
"https://localhost:5001/api/services/status"
);
response.EnsureSuccessStatusCode();
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);The client loads its certificate from a PFX file and adds it to the HttpClientHandler.
When the HTTPS connection is established, the handler can present the certificate to the server during the TLS handshake.
In production, avoid storing certificate passwords directly in source code or configuration files committed to source control. Use an appropriate secrets management system or operating-system certificate store.
Also, do not disable server certificate validation to make local testing easier. The client must still verify that it is communicating with the intended API server.
Client Certificate Authentication Behind a Reverse Proxy
Many production ASP.NET Core applications run behind reverse proxies, API gateways, or load balancers.
In these environments, the proxy may terminate the original HTTPS connection before forwarding the request to the ASP.NET Core application.
This creates an important challenge: the backend application may no longer receive the original client certificate through its own TLS connection.
There are two common approaches.
The first approach is to perform client certificate authentication at the reverse proxy and securely forward verified certificate information to the backend.
The second approach is to configure TLS passthrough so that the original TLS connection reaches the application server.
When forwarding certificate information through HTTP headers, the backend must trust only the configured proxy. The proxy must remove any client-supplied certificate headers and replace them with verified information. Direct access to the backend must also be restricted.
Never trust an arbitrary certificate header received from an untrusted client. Otherwise, an attacker may be able to impersonate another service.
Best Practices for Client Certificate Authentication
Use a Trusted Certificate Authority
Issue client certificates through a trusted internal or external certificate authority. Avoid accepting arbitrary self-signed certificates in production.
Maintain a clear process for certificate issuance and ownership.
Validate Certificate Expiration and Revocation
A certificate that was valid when issued may later expire or be revoked.
Configure appropriate revocation checking and monitor the availability of certificate revocation infrastructure.
Use Stable Client Identification
Do not depend entirely on certificate subject names for identifying services.
Use an approved certificate registry or another stable identifier that can be checked during authentication.
Plan Certificate Renewal
Certificates have limited validity periods. Create a renewal process that allows new certificates to be deployed before existing certificates expire.
During certificate rotation, consider a controlled overlap period in which both the old and new certificates are accepted.
Protect Private Keys
The private key associated with a client certificate must remain confidential.
Use secure certificate stores, restricted file permissions, or hardware-backed key storage where appropriate.
Combine Authentication With Authorization
A valid certificate should not automatically provide access to every API endpoint.
Use authorization policies to control which services can perform specific operations.
Common Mistakes to Avoid
One common mistake is configuring certificate authentication without configuring the HTTPS server to request client certificates. The authentication handler cannot validate a certificate that the connection never provides.
Another mistake is assuming that every certificate issued by a trusted authority should be allowed to access every endpoint. Trusting an issuer and authorizing a particular client are separate decisions.
Developers also sometimes disable certificate revocation checks without understanding the security implications. This can allow a revoked certificate to remain usable until it expires.
Finally, avoid storing PFX passwords or private keys directly in application source code. Certificate material should be managed securely throughout its lifecycle.
Troubleshooting Common Issues
| Problem | Possible Reason | Solution |
|---|---|---|
| Client certificate is not received | Kestrel is not requesting certificates | Configure ClientCertificateMode |
| Authentication fails | Certificate chain is not trusted | Check the certificate authority and chain |
| HTTPS connection fails | Client does not provide a required certificate | Configure the client certificate correctly |
| Certificate is rejected | Certificate has expired or been revoked | Renew the certificate or investigate revocation status |
| API returns 401 | Certificate authentication did not succeed | Review authentication configuration and logs |
| API returns 403 | Client is authenticated but not authorized | Review authorization policies |
| Certificate works locally but not in production | Reverse proxy or TLS termination changes certificate handling | Review proxy and certificate forwarding configuration |
When troubleshooting, inspect the TLS configuration, certificate chain, authentication logs, and proxy settings. This helps identify whether the issue occurs during the HTTPS handshake, certificate validation, or application authorization.
Advantages and Disadvantages
Advantages
- Provides strong machine-to-machine authentication.
- Uses digital certificates instead of relying only on shared API keys.
- Supports mutual TLS authentication.
- Helps identify trusted applications and services.
- Integrates with ASP.NET Core authentication and authorization.
- Works well for controlled enterprise environments.
Disadvantages
- Certificate issuance and renewal require additional management.
- Expired or revoked certificates can interrupt service communication.
- Private keys must be securely stored and protected.
- Reverse proxy configurations can make certificate forwarding more complex.
- Certificate validation can introduce additional infrastructure dependencies.
- Managing certificates across many services requires proper operational planning.
Summary
Client certificate authentication provides an additional security mechanism for ASP.NET Core APIs, particularly when applications communicate with trusted internal services or external enterprise systems.
By using the certificate authentication handler, developers can validate incoming certificates, establish authenticated client identities, and protect API endpoints through authorization policies.
A reliable implementation requires more than registering an authentication handler. The HTTPS server must request client certificates, the certificate chain must be validated, and application-specific authorization rules must determine which clients can access protected resources.
For production applications, certificate renewal, revocation checking, private key protection, and reverse proxy configuration should all be part of the security design.
When implemented correctly, client certificate authentication helps build a stronger trust relationship between services and provides a practical foundation for securing machine-to-machine communication in ASP.NET Core.

Join the conversation! Your thoughts help the community grow.