Securing an API is not limited to validating usernames, passwords, or access tokens. Some applications need an additional level of protection to verify which system is connecting to the server.
Consider an enterprise application where multiple internal services communicate with an ASP.NET Core API. One service retrieves customer information, another submits payment requests, and a third processes financial reports. Even if these services use HTTPS, the API may need a reliable way to verify that the connecting client is an approved application.
Client certificates provide one way to establish this trust.
With mutual TLS (mTLS), both the server and the client present certificates during the TLS handshake. The server validates the client's certificate before allowing the connection to proceed.
This approach is useful for service-to-service communication, enterprise integrations, internal APIs, and environments where access should be restricted to registered systems.
In this article, we will explore how client certificates work, configure certificate authentication in ASP.NET Core, validate incoming certificates, and handle common production scenarios.
What Is Client Certificate Authentication?
In normal HTTPS communication, the server presents its TLS certificate to the client. The client validates that certificate to confirm it is communicating with the intended server.
Client certificate authentication adds another step.
The client also presents a certificate, allowing the server to verify the identity of the connecting client.
This is commonly called mutual TLS because both sides participate in certificate-based authentication.
<text></text>
The basic communication flow looks like this:
Client Application
|
| 1. Starts HTTPS connection
|
v
ASP.NET Core API
|
| 2. Requests client certificate
|
v
Client Application
|
| 3. Sends client certificate
|
v
Certificate Validation
|
| 4. Validates certificate
|
v
API Authentication
|
| 5. Creates authenticated identity
|
v
Protected API EndpointThe certificate helps establish which client is connecting. The API can then use that identity to decide whether the client is authorized to access a particular resource.
It is important to understand that a valid certificate does not automatically mean that the client should have access to every API endpoint. Authentication and authorization are separate responsibilities.
When Should You Use Client Certificates?
Client certificates are particularly useful when the API communicates with known systems rather than unrestricted public clients.
Common scenarios include:
Service-to-Service Communication
An order service may need to call a payment API. Instead of relying only on a shared API key, the payment API can require a trusted client certificate.
Enterprise Integrations
Organizations often connect internal applications with external business systems. Client certificates can help identify registered integration partners.
Internal APIs
An API used by a limited number of internal applications may require certificate authentication to prevent unauthorized systems from connecting.
Sensitive Business Operations
Financial operations, customer data access, and administrative integrations may require stronger client identity verification.
Client certificates are not always necessary for ordinary public APIs. For applications where users authenticate individually, OAuth 2.0 or OpenID Connect may be more appropriate. Client certificates can also be combined with token-based authentication when both application identity and user identity are required.
Understanding the Certificate Requirements
Before configuring ASP.NET Core, it helps to understand the certificates involved.
A typical client certificate contains information such as:
Subject identifying the certificate owner.
Issuer identifying the certificate authority.
Public key used during certificate-based authentication.
Validity period.
Key usage and extended key usage.
Serial number.
Thumbprint.
The client also has access to the corresponding private key. The private key is used during the TLS handshake to prove possession of the certificate.
The server should trust the certificate authority that issued the client certificate.
For production systems, certificates should generally be issued by an organization-approved certificate authority rather than using arbitrary self-signed certificates.
A self-signed certificate can be useful for local development and controlled testing, but production trust should be managed carefully.
Creating Certificates for Local Development
For local testing, you can create a development certificate using OpenSSL.
Generate a private key:
openssl genrsa -out client.key 2048Create a certificate signing request:
openssl req -new \
-key client.key \
-out client.csr \
-subj "/CN=internal-client"For a simple local test, generate a self-signed certificate:
openssl x509 -req \
-in client.csr \
-signkey client.key \
-out client.crt \
-days 365 \
-sha256The resulting files include:
client.key: The client's private key.
client.crt: The client certificate.
client.csr: The certificate signing request.
For a real environment, use a trusted certificate authority and configure the required certificate extensions, including client authentication usage.
The private key must never be distributed with the public certificate.
Configuring Client Certificate Authentication in ASP.NET Core
ASP.NET Core provides certificate authentication support through the Microsoft.AspNetCore.Authentication.Certificate package.
Install the package:
dotnet add package Microsoft.AspNetCore.Authentication.CertificateNext, configure certificate authentication in Program.cs.
using Microsoft.AspNetCore.Authentication.Certificate;
using System.Security.Claims;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services
.AddAuthentication(
CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate(options =>
{
options.AllowedCertificateTypes =
CertificateTypes.Chained;
options.ValidateCertificateUse = true;
options.ValidateValidityPeriod = true;
options.RevocationMode =
System.Security.Cryptography.X509Certificates
.X509RevocationMode.Online;
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();Let's understand the important configuration settings.
AllowedCertificateTypes
This setting controls which certificate types are accepted.
In this example, only certificates that can be validated through a certificate chain are accepted.
For production systems, this is generally preferable to accepting arbitrary self-signed certificates.
ValidateCertificateUse
This setting checks whether the certificate is intended for the required usage.
The certificate should be suitable for client authentication.
ValidateValidityPeriod
This setting ensures that the certificate is within its validity period.
An expired or not-yet-valid certificate should not be accepted.
RevocationMode
Certificate revocation checking helps identify certificates that have been revoked before their expiration date.
Online revocation checking can introduce network dependencies and latency. Its behavior should be tested with the certificate authority and infrastructure used by the application.
Protecting an API Endpoint With a Client Certificate
After configuring authentication, an endpoint can require certificate authentication.
Consider the following controller:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/secure")]
public class SecureController : ControllerBase
{
[Authorize]
[HttpGet("customer-data")]
public IActionResult GetCustomerData()
{
return Ok(new
{
Message = "Client certificate authentication successful",
Client = User.Identity?.Name
});
}
}When a client calls this endpoint, ASP.NET Core requires an authenticated identity.
If the client does not provide a valid certificate, authentication fails and the protected endpoint cannot be accessed.
However, the authentication configuration should be tested carefully with the actual hosting environment. The application must receive the client certificate through the HTTPS connection.
Restricting Access to Specific Client Certificates
Certificate authentication verifies that a certificate is trusted and valid according to the configured rules.
However, an organization may need to restrict API access to a specific set of registered clients.
For example, suppose only the OrderService and PaymentService applications should access a particular API.
A certificate validation event can perform additional checks.
builder.Services
.AddAuthentication(
CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate(options =>
{
options.Events =
new CertificateAuthenticationEvents
{
OnCertificateValidated = context =>
{
var certificate = context.ClientCertificate;
var allowedClient =
certificate.Subject.Contains(
"CN=internal-client",
StringComparison.OrdinalIgnoreCase);
if (!allowedClient)
{
context.Fail(
"Client certificate is not registered.");
return Task.CompletedTask;
}
var claims = new[]
{
new Claim(
ClaimTypes.Name,
"InternalClient")
};
var identity = new ClaimsIdentity(
claims,
context.Scheme.Name);
context.Principal =
new ClaimsPrincipal(identity);
context.Success();
return Task.CompletedTask;
}
};
});This example demonstrates how a certificate can be checked against an application-specific rule.
However, checking only the certificate subject is not a strong production identity strategy. Subjects can be duplicated or formatted differently.
A better approach is to maintain an approved certificate registry and validate a stable certificate identifier, such as a thumbprint or serial number combined with the expected issuer.
For larger systems, consider certificate rotation and renewal when designing this registry.
Sending a Client Certificate From an Application
The client application must attach its certificate when establishing the HTTPS connection.
For a .NET application, HttpClientHandler supports client certificates.
Consider the following example:
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
var certificate = new X509Certificate2(
"client.pfx",
"certificate-password");
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);
using var client = new HttpClient(handler);
var response = await client.GetAsync(
"https://localhost:7001/api/secure/customer-data");
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);The PFX file contains the client certificate and its private key.
In this example, the certificate password is shown directly to keep the code understandable. In production, store certificate passwords and private keys in an appropriate secure secret or certificate-management system.
Also, avoid creating a new HttpClient for every request in a production application. Use IHttpClientFactory or a properly managed long-lived client configuration so that connection pooling and certificate handling remain predictable.
Handling Client Certificates in ASP.NET Core Hosting Environments
One important detail is that certificate authentication depends on the TLS connection.
The component that terminates HTTPS must make the client certificate available to ASP.NET Core.
This can become more complicated when the API runs behind a reverse proxy, load balancer, or API gateway.
For example:
External Client
|
| HTTPS with client certificate
|
v
Load Balancer / Reverse Proxy
|
| Forwarded request
|
v
ASP.NET Core APIIf the reverse proxy terminates TLS, the ASP.NET Core application may not receive the original TLS client certificate automatically.
There are two common approaches.
TLS Termination at the ASP.NET Core Application
The application handles the HTTPS connection directly.
In this setup, the hosting server can provide the client certificate through the TLS connection.
This is a straightforward option when the application controls the HTTPS endpoint.
TLS Termination at a Reverse Proxy
The reverse proxy validates the client certificate and forwards trusted certificate information to the backend.
This setup requires careful configuration.
Certificate information forwarded through HTTP headers must not be accepted from arbitrary external requests. The backend should only trust such information when it comes from a properly secured and trusted proxy that removes untrusted incoming certificate headers.
The proxy-to-application connection should also be protected, and the application should not be directly accessible in a way that bypasses the proxy's certificate checks.
Certificate Renewal and Rotation
Certificates have expiration dates, so a production system needs a renewal strategy.
If a certificate expires without being replaced, clients may suddenly lose access to the API.
A practical certificate management process should include:
Maintain an inventory of certificates used by client applications.
Record certificate expiration dates and issuing authorities.
Begin renewal before certificates expire.
Register the replacement certificate before switching clients.
Test the new certificate against the production validation rules.
Remove the old certificate after all dependent clients have migrated.
During certificate rotation, it may be necessary to accept both the old and new certificates temporarily.
This allows clients to migrate without requiring every application to update at exactly the same time.
Avoid using a single certificate indefinitely across unrelated services. Separate client identities make access control and certificate replacement easier to manage.
Common Mistakes to Avoid
Mistake | Impact | Recommended Approach |
|---|---|---|
Accepting every client certificate | Unknown applications may connect | Validate trusted issuers and registered clients |
Checking only the certificate subject | Different certificates may use similar subjects | Use a controlled certificate registry |
Ignoring expiration dates | Clients may suddenly lose access | Monitor and renew certificates early |
Disabling certificate validation | Removes important security checks | Keep certificate validation enabled |
Trusting forwarded certificate headers from any request | Attackers may impersonate trusted clients | Trust only secured, configured proxies |
Sharing private keys between unrelated services | Compromises multiple client identities | Use separate certificates and private keys |
Forgetting certificate revocation | Revoked certificates may remain usable | Configure and test revocation handling |
Troubleshooting Client Certificate Authentication
The API Does Not Receive a Client Certificate
Check whether the HTTPS endpoint requests client certificates and whether the hosting environment forwards the certificate correctly.
If a reverse proxy terminates TLS, review its certificate forwarding configuration.
The Certificate Chain Is Not Trusted
Verify that the issuing certificate authority is trusted by the server.
Also check that intermediate certificates are available so the server can build the complete certificate chain.
The Certificate Has Expired
Check the certificate validity period and replace the certificate with a renewed version.
Ensure that client applications receive the replacement certificate before the previous one expires.
Certificate Revocation Checking Fails
Verify that the server can access the certificate authority's revocation information, such as CRL or OCSP endpoints.
Network restrictions or unavailable revocation services can affect online certificate validation.
Authentication Works Locally but Fails in Production
Compare the local and production TLS configurations.
Check reverse proxy settings, trusted certificate authorities, certificate chain availability, and the way client certificates are forwarded to the application.
Summary
Client certificate authentication provides a way for ASP.NET Core APIs to verify the identity of connecting applications through mutual TLS. It is especially useful for service-to-service communication, enterprise integrations, and internal APIs that need stronger client identity verification.
ASP.NET Core supports certificate authentication through the Microsoft.AspNetCore.Authentication.Certificate package. Developers can configure certificate validation, protect endpoints with authorization, and apply additional rules to identify approved client applications.
For production systems, certificate authentication should be treated as part of a broader security strategy. Trusted certificate authorities, private key protection, certificate renewal, revocation checks, and secure reverse proxy configuration are all important.
When implemented correctly, client certificates help establish trusted communication between systems without requiring every integration to depend on a shared API key.


Join the conversation! Your thoughts help the community grow.