Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Microsoft.AspNetCore.Authentication.Certificate contains an implementation similar to Certificate Authentication for ASP.NET Core. Certificate authentication happens at the TLS level before it ever gets to ASP.NET Core. More accurately, this functionality is an authentication handler that validates the certificate and then gives you an event where you can resolve that certificate to a ClaimsPrincipal.
You must configure your server for certificate authentication with IIS, Kestrel, Azure Web Apps, or your preferred solution.
This article describes how to configure certificate authentication in ASP.NET Core for IIS and HTTP.sys, and provides examples for calling various methods and working with properties.
Review proxy and load balancer scenarios
Certificate authentication is a stateful scenario primarily used where a proxy or load balancer doesn't handle traffic between clients and servers. If a proxy or load balancer is used, certificate authentication only works if the proxy or load balancer:
- Handles the authentication.
- Passes the user authentication information to the app (for example, in a request header), which acts on the authentication information.
An alternative to certificate authentication in environments where proxies and load balancers are used is Active Directory Federated Services (ADFS) with OpenID Connect (OIDC).
Get started
Acquire an HTTPS certificate, apply it, and configure your server to require certificates.
In the web app:
Add a reference to the Microsoft.AspNetCore.Authentication.Certificate NuGet package.
In the Program.cs file, call the
builder.Services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme).AddCertificate(...);method. Provide a delegate for theOnCertificateValidatedevent handler to complete any supplementary validation on the client certificate sent with requests. Turn that information into aClaimsPrincipalvalue and set it on thecontext.Principalproperty.
If authentication fails, this handler returns a 403 (Forbidden) response rather than a 401 (Unauthorized), as you might expect. The handler returns a different response because it expects authentication to occur during the initial TLS connection. By the time it reaches the handler, it's too late. There's no way to upgrade the connection from an anonymous connection to one with a certificate.
The UseAuthentication method is required to set HttpContext.User to a ClaimsPrincipal value created from the certificate. For example:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(
CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate();
var app = builder.Build();
app.UseAuthentication();
app.MapGet("/", () => "Hello World!");
app.Run();
The preceding example demonstrates the default way to add certificate authentication. The handler constructs a user principal by using the common certificate properties.
Configure certificate validation
The CertificateAuthenticationOptions handler has some built-in validations that are the minimum validations you should perform on a certificate. Each of these settings is enabled by default. The following sections describe how to work with the settings.
AllowedCertificateTypes = Chained, SelfSigned, or All (Chained | SelfSigned)
Default value: CertificateTypes.Chained
This check validates that only the appropriate certificate type is allowed. If the app is using self-signed certificates, this option needs to be set to CertificateTypes.All or CertificateTypes.SelfSigned.
ChainTrustValidationMode
Default value: X509ChainTrustMode.System
The certificate presented by the client must chain to a trusted root certificate. This check controls which trust store contains these root certificates.
By default, the handler uses the system trust store. If the presented client certificate needs to chain to a root certificate that doesn't appear in the system trust store, you can set the option to X509ChainTrustMode.CustomRootTrust so the handler uses the CustomTrustStore property.
CustomTrustStore
Default value: Empty X509Certificate2Collection
If the handler's ChainTrustValidationMode property is set to X509ChainTrustMode.CustomRootTrust, this X509Certificate2Collection object contains every certificate used to validate the client certificate up to a trusted root, including the trusted root.
When the client presents a certificate that's part of a multi-level certificate chain, the CustomTrustStore property must contain every issuing certificate in the chain.
ValidateCertificateUse
Default value: true
This check validates that the certificate presented by the client has the Client Authentication extended key use (EKU), or no EKUs at all. As the specifications say, if no EKU is specified, then all EKUs are deemed valid.
ValidateValidityPeriod
Default value: true
This check validates that the certificate is within its validity period. On each request, the handler ensures that a certificate that was valid when it was presented hasn't expired during its current session.
RevocationFlag
Default value: X509RevocationFlag.ExcludeRoot
A flag that specifies which certificates in the chain are checked for revocation.
Revocation checks are only performed when the certificate is chained to a root certificate.
RevocationMode
Default value: X509RevocationMode.Online
A flag that specifies how revocation checks are performed.
Specifying an online check can result in a long delay while the certificate authority is contacted.
Revocation checks are performed only when the certificate is chained to a root certificate.
FAQ: Can I configure my app to require a certificate only on certain paths?
This approach isn't possible. The certificate exchange is completed at the start of the HTTPS conversation. The operation is done by the server before the first request is received on that connection, so it isn't possible to scope based on any request fields.
Process handler events
The handler has two events:
OnAuthenticationFailed: Called if an exception happens during authentication and allows you to react.OnCertificateValidated: Called after the certificate is validated, passed validation, and a default principal is created. This event allows you to perform your own validation and augment or replace the principal. Examples include:Determining if the certificate is known to your services.
Constructing your own principal, such as in the following example:
builder.Services.AddAuthentication( CertificateAuthenticationDefaults.AuthenticationScheme) .AddCertificate(options => { 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) }; context.Principal = new ClaimsPrincipal( new ClaimsIdentity(claims, context.Scheme.Name)); context.Success(); return Task.CompletedTask; } }; });
If the inbound certificate doesn't satisfy your extra validation, call context.Fail("failure reason") with a failure reason.
For better functionality, call a service registered in dependency injection that connects to a database or other type of user store. Access the service by using the context passed into the delegate. Consider the following example:
builder.Services.AddAuthentication(
CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate(options =>
{
options.Events = new CertificateAuthenticationEvents
{
OnCertificateValidated = context =>
{
var validationService = context.HttpContext.RequestServices
.GetRequiredService<ICertificateValidationService>();
if (validationService.ValidateCertificate(context.ClientCertificate))
{
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)
};
context.Principal = new ClaimsPrincipal(
new ClaimsIdentity(claims, context.Scheme.Name));
context.Success();
}
return Task.CompletedTask;
}
};
});
Conceptually, the validation of the certificate is an authorization concern. For example, you can add a check on an issuer or thumbprint in an authorization policy rather than inside the OnCertificateValidated handler.
Configure your server to require certificates
The following sections describe how to configure your server to require certificates for a specific solution, including Kestrel, IIS, Azure, custom web proxies, and Azure Web Apps.
Kestrel
In the Program.cs file, configure Kestrel as follows:
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<KestrelServerOptions>(options =>
{
options.ConfigureHttpsDefaults(options =>
options.ClientCertificateMode = ClientCertificateMode.RequireCertificate);
});
Note
When an endpoint is created by calling the Listen method before calling the ConfigureHttpsDefaults method, the endpoint doesn't have the defaults applied.
IIS
Complete the following steps in IIS Manager:
- In the Connections tab, select your site.
- In the Features View window, double-click SSL Settings.
- Select the Require SSL checkbox.
- For the Client certificates option, select Require.
Azure and custom web proxies
For more information on how to configure the certificate forwarding middleware, see the host and deploy documentation.
Certificate authentication in Azure Web Apps
No forwarding configuration is required for Azure. The certificate-forwarding middleware sets up the configuration.
Note
Certificate-forwarding middleware is required for this scenario.
For more information, see Use TLS/SSL certificates in your app code (Azure documentation).
Certificate authentication in custom web proxies
The AddCertificateForwarding method is used to specify:
- The client header name.
- How to load the certificate (via the
HeaderConverterproperty).
In custom web proxies, the certificate is passed as a custom request header, for example X-SSL-CERT. To use the certificate, configure certificate forwarding in the Program.cs file:
builder.Services.AddCertificateForwarding(options =>
{
options.CertificateHeader = "X-SSL-CERT";
options.HeaderConverter = headerValue =>
{
X509Certificate2? clientCertificate = null;
if (!string.IsNullOrWhiteSpace(headerValue))
{
clientCertificate = new X509Certificate2(StringToByteArray(headerValue));
}
return clientCertificate!;
static byte[] StringToByteArray(string hex)
{
var numberChars = hex.Length;
var bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
};
});
If NGINX is used with the configuration proxy_set_header ssl-client-cert $ssl_client_escaped_cert to reverse proxy the app, or the app is deployed on Kubernetes by using NGINX Ingress, the client certificate is passed to the app in URL-encoded form. To use the certificate, decode it as follows:
builder.Services.AddCertificateForwarding(options =>
{
options.CertificateHeader = "ssl-client-cert";
options.HeaderConverter = (headerValue) =>
{
X509Certificate2? clientCertificate = null;
if (!string.IsNullOrWhiteSpace(headerValue))
{
clientCertificate = X509Certificate2.CreateFromPem(
WebUtility.UrlDecode(headerValue));
}
return clientCertificate!;
};
});
Add the middleware in the Program.cs file. The UseCertificateForwarding method is called before the calls to the UseAuthentication and UseAuthorization methods:
var app = builder.Build();
app.UseCertificateForwarding();
app.UseAuthentication();
app.UseAuthorization();
A separate class can be used to implement validation logic. Because the same self-signed certificate is used in this example, ensure that only your certificate can be used. Validate that the thumbprints of both the client certificate and the server certificate match. Otherwise, any certificate can be used and be sufficient for authentication. The certificate is then used inside the AddCertificate method. You can also validate the subject or the issuer here if you use intermediate or child certificates.
using System.Security.Cryptography.X509Certificates;
namespace CertAuthSample.Snippets;
public class SampleCertificateValidationService : ICertificateValidationService
{
public bool ValidateCertificate(X509Certificate2 clientCertificate)
{
// Don't hardcode passwords in production code.
// Use a certificate thumbprint or Azure Key Vault.
var expectedCertificate = new X509Certificate2(
Path.Combine("/path/to/pfx"), "1234");
return clientCertificate.Thumbprint == expectedCertificate.Thumbprint;
}
}
Implement an HttpClient with a certificate and IHttpClientFactory
In the following example, a client certificate is added to a HttpClientHandler by using the ClientCertificates property from the handler. This handler can then be used in a named instance of an HttpClient with the ConfigurePrimaryHttpMessageHandler method. This scenario is configured in the Program.cs file:
var clientCertificate =
new X509Certificate2(
Path.Combine(_environment.ContentRootPath, "sts_dev_cert.pfx"), "1234");
builder.Services.AddHttpClient("namedClient", c =>
{
}).ConfigurePrimaryHttpMessageHandler(() =>
{
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(clientCertificate);
return handler;
});
The IHttpClientFactory can then be used to get the named instance with the handler and the certificate. The CreateClient method with the name of the client defined in the Program.cs file is used to get the instance. The HTTP request can be sent by using the client as required:
public class SampleHttpService
{
private readonly IHttpClientFactory _httpClientFactory;
public SampleHttpService(IHttpClientFactory httpClientFactory)
=> _httpClientFactory = httpClientFactory;
public async Task<JsonDocument> GetAsync()
{
var httpClient = _httpClientFactory.CreateClient("namedClient");
var httpResponseMessage = await httpClient.GetAsync("https://example.com");
if (httpResponseMessage.IsSuccessStatusCode)
{
return JsonDocument.Parse(
await httpResponseMessage.Content.ReadAsStringAsync());
}
throw new ApplicationException($"Status code: {httpResponseMessage.StatusCode}");
}
}
If the correct certificate is sent to the server, the data is returned. If no certificate or the wrong certificate is sent, the server returns an HTTP 403 status code.
Certificates in PowerShell
Creating the certificates is the hardest part in setting up this flow. You can create a root certificate by using the New-SelfSignedCertificate PowerShell cmdlet. When you create the certificate, use a strong password. It's important to add the KeyUsageProperty parameter and the KeyUsage parameter as shown in the examples.
Create root certificate authority
The following code shows how to create a certificate authority (CA) at the root:
New-SelfSignedCertificate -DnsName "root_ca_dev_damienbod.com", "root_ca_dev_damienbod.com" -CertStoreLocation "cert:\LocalMachine\My" -NotAfter (Get-Date).AddYears(20) -FriendlyName "root_ca_dev_damienbod.com" -KeyUsageProperty All -KeyUsage CertSign, CRLSign, DigitalSignature
$mypwd = ConvertTo-SecureString -String "1234" -Force -AsPlainText
Get-ChildItem -Path cert:\localMachine\my\"The thumbprint..." | Export-PfxCertificate -FilePath C:\git\root_ca_dev_damienbod.pfx -Password $mypwd
Export-Certificate -Cert cert:\localMachine\my\"The thumbprint..." -FilePath root_ca_dev_damienbod.crt
Note
The -DnsName parameter value must match the deployment target of the app. For example, "localhost" for development.
Install in the trusted root
The root certificate must be trusted on your host system. Only root certificates created by a certificate authority are trusted by default. For information on how to trust the root certificate on Windows, see the Windows documentation or the Import-Certificate PowerShell cmdlet.
Use an intermediate certificate
An intermediate certificate can now be created from the root certificate. This approach isn't required for all use cases, but you might need to create many certificates or need to activate or disable groups of certificates. The TextExtension parameter is required to set the path length in the basic constraints of the certificate.
The intermediate certificate can then be added to the trusted intermediate certificate in the Windows host system.
$mypwd = ConvertTo-SecureString -String "1234" -Force -AsPlainText
$parentcert = ( Get-ChildItem -Path cert:\LocalMachine\My\"The thumbprint of the root..." )
New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname "intermediate_dev_damienbod.com" -Signer $parentcert -NotAfter (Get-Date).AddYears(20) -FriendlyName "intermediate_dev_damienbod.com" -KeyUsageProperty All -KeyUsage CertSign, CRLSign, DigitalSignature -TextExtension @("2.5.29.19={text}CA=1&pathlength=1")
Get-ChildItem -Path cert:\localMachine\my\"The thumbprint..." | Export-PfxCertificate -FilePath C:\git\AspNetCoreCertificateAuth\Certs\intermediate_dev_damienbod.pfx -Password $mypwd
Export-Certificate -Cert cert:\localMachine\my\"The thumbprint..." -FilePath intermediate_dev_damienbod.crt
Create child certificate from intermediate certificate
A child certificate can be created from the intermediate certificate. This child certificate is the end entity. You don't need to create more child certificates.
$parentcert = ( Get-ChildItem -Path cert:\LocalMachine\My\"The thumbprint from the Intermediate certificate..." )
New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname "child_a_dev_damienbod.com" -Signer $parentcert -NotAfter (Get-Date).AddYears(20) -FriendlyName "child_a_dev_damienbod.com"
$mypwd = ConvertTo-SecureString -String "1234" -Force -AsPlainText
Get-ChildItem -Path cert:\localMachine\my\"The thumbprint..." | Export-PfxCertificate -FilePath C:\git\AspNetCoreCertificateAuth\Certs\child_a_dev_damienbod.pfx -Password $mypwd
Export-Certificate -Cert cert:\localMachine\my\"The thumbprint..." -FilePath child_a_dev_damienbod.crt
Create child certificate from root certificate
A child certificate can also be created from the root certificate directly.
$rootcert = ( Get-ChildItem -Path cert:\LocalMachine\My\"The thumbprint from the root cert..." )
New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname "child_a_dev_damienbod.com" -Signer $rootcert -NotAfter (Get-Date).AddYears(20) -FriendlyName "child_a_dev_damienbod.com"
$mypwd = ConvertTo-SecureString -String "1234" -Force -AsPlainText
Get-ChildItem -Path cert:\localMachine\my\"The thumbprint..." | Export-PfxCertificate -FilePath C:\git\AspNetCoreCertificateAuth\Certs\child_a_dev_damienbod.pfx -Password $mypwd
Export-Certificate -Cert cert:\localMachine\my\"The thumbprint..." -FilePath child_a_dev_damienbod.crt
Example: root - intermediate certificate - certificate
The following example shows configuration of the root CA, the intermediate certificate, and the child certificate:
$mypwdroot = ConvertTo-SecureString -String "1234" -Force -AsPlainText
$mypwd = ConvertTo-SecureString -String "1234" -Force -AsPlainText
New-SelfSignedCertificate -DnsName "root_ca_dev_damienbod.com", "root_ca_dev_damienbod.com" -CertStoreLocation "cert:\LocalMachine\My" -NotAfter (Get-Date).AddYears(20) -FriendlyName "root_ca_dev_damienbod.com" -KeyUsageProperty All -KeyUsage CertSign, CRLSign, DigitalSignature
Get-ChildItem -Path cert:\localMachine\my\0C89639E4E2998A93E423F919B36D4009A0F9991 | Export-PfxCertificate -FilePath C:\git\root_ca_dev_damienbod.pfx -Password $mypwdroot
Export-Certificate -Cert cert:\localMachine\my\0C89639E4E2998A93E423F919B36D4009A0F9991 -FilePath root_ca_dev_damienbod.crt
$rootcert = ( Get-ChildItem -Path cert:\LocalMachine\My\0C89639E4E2998A93E423F919B36D4009A0F9991 )
New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname "child_a_dev_damienbod.com" -Signer $rootcert -NotAfter (Get-Date).AddYears(20) -FriendlyName "child_a_dev_damienbod.com" -KeyUsageProperty All -KeyUsage CertSign, CRLSign, DigitalSignature -TextExtension @("2.5.29.19={text}CA=1&pathlength=1")
Get-ChildItem -Path cert:\localMachine\my\BA9BF91ED35538A01375EFC212A2F46104B33A44 | Export-PfxCertificate -FilePath C:\git\AspNetCoreCertificateAuth\Certs\child_a_dev_damienbod.pfx -Password $mypwd
Export-Certificate -Cert cert:\localMachine\my\BA9BF91ED35538A01375EFC212A2F46104B33A44 -FilePath child_a_dev_damienbod.crt
$parentcert = ( Get-ChildItem -Path cert:\LocalMachine\My\BA9BF91ED35538A01375EFC212A2F46104B33A44 )
New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname "child_b_from_a_dev_damienbod.com" -Signer $parentcert -NotAfter (Get-Date).AddYears(20) -FriendlyName "child_b_from_a_dev_damienbod.com"
Get-ChildItem -Path cert:\localMachine\my\141594A0AE38CBBECED7AF680F7945CD51D8F28A | Export-PfxCertificate -FilePath C:\git\AspNetCoreCertificateAuth\Certs\child_b_from_a_dev_damienbod.pfx -Password $mypwd
Export-Certificate -Cert cert:\localMachine\my\141594A0AE38CBBECED7AF680F7945CD51D8F28A -FilePath child_b_from_a_dev_damienbod.crt
When you use the root, intermediate, or child certificates, the certificates can be validated by using the Thumbprint or PublicKey as required:
using System.Security.Cryptography.X509Certificates;
namespace CertAuthSample.Snippets;
public class SampleCertificateThumbprintsValidationService : ICertificateValidationService
{
private readonly string[] validThumbprints = new[]
{
"141594A0AE38CBBECED7AF680F7945CD51D8F28A",
"0C89639E4E2998A93E423F919B36D4009A0F9991",
"BA9BF91ED35538A01375EFC212A2F46104B33A44"
};
public bool ValidateCertificate(X509Certificate2 clientCertificate)
=> validThumbprints.Contains(clientCertificate.Thumbprint);
}
Cache certificate validation results
.NET 5 and later versions support the ability to enable caching of validation results. The caching dramatically improves performance of certificate authentication because validation is an expensive operation.
By default, certificate authentication disables caching. To enable caching, call the AddCertificateCache method in the Program.cs file:
builder.Services.AddAuthentication(
CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate()
.AddCertificateCache(options =>
{
options.CacheSize = 1024;
options.CacheEntryExpiration = TimeSpan.FromMinutes(2);
});
When AddCertificateCache is enabled, the result produced by OnCertificateValidated must be a pure function of the authentication scheme and certificate. Don't base the result on request context because the cached result is reused for subsequent requests. Place request-context-dependent decisions in an authorization policy or provide a context-aware implementation of ICertificateValidationCache.
The cache stores both successful and failed validation results for the configured cache entry lifetime.
The default caching implementation stores results in memory. You can provide your own cache by implementing ICertificateValidationCache and registering it with dependency injection. For example, services.AddSingleton<ICertificateValidationCache, YourCache>().
Use optional client certificates
This section provides information for apps that must protect a subset of the app with a certificate. For example, a Razor Page or controller in the app might require client certificates. This scenario presents some challenges:
- Client certificates are a TLS feature, not an HTTP feature.
- Client certificates are negotiated per-connection and usually at the start of the connection before any HTTP data is available.
There are two approaches for implementing optional client certificates:
- Option 1: Use separate host names (SNI) and redirection. While this option involves more work to configure, the approach is recommended because it works in most environments and protocols.
- Option 2: Renegotiation during an HTTP request. This approach has several limitations and isn't recommended.
Separate hosts (SNI)
At the start of the connection, only the Server Name Indication (SNI)† is known. Client certificates can be configured per host name so one host requires the certificates and another doesn't.
Set up binding for the domain and subdomain.
For example, set up bindings on
contoso.comandmyClient.contoso.com. Thecontoso.comhost doesn't require a client certificate butmyClient.contoso.comdoes.For more information, see the following resources:
IIS
HTTP.sys
.NET 5 and later offers more convenient support for redirecting to acquire optional client certificates. For more information, see the Optional certificates sample.
For requests to the web app that require a client certificate and don't have one, redirect to the same page by using the client certificate protected subdomain.
For example, redirect to
myClient.contoso.com/requestedPage. Because the request tomyClient.contoso.com/requestedPageis a different hostname thancontoso.com/requestedPage, the client establishes a different connection and the client certificate is provided.For more information, see Introduction to authorization in ASP.NET Core.
† Server Name Indication (SNI) is a TLS extension that's used to include a virtual domain as a part of SSL negotiation. This approach effectively means the virtual domain name, or a hostname, can be used to identify the network end point.
TLS renegotiation
TLS renegotiation is a process by which the client and server can reassess the encryption requirements for an individual connection, including requesting a client certificate if not previously provided. TLS renegotiation is a security risk and isn't recommended because:
- In HTTP/1.1, the server must first buffer or consume any in-flight HTTP data such as POST request bodies to make sure the connection is clear for the renegotiation. Otherwise, the renegotiation can stop responding or fail.
- HTTP/2 and HTTP/3 explicitly prohibit renegotiation.
- There are security risks associated with renegotiation. TLS 1.3 removed renegotiation of the whole connection and replaced it with a new extension for requesting only the client certificate after the start of the connection. This mechanism is exposed via the same APIs and is still subject to the prior constraints of buffering and HTTP protocol versions.
The implementation and configuration of this feature varies by server and framework version, as described in the following sections.
IIS
IIS manages the client certificate negotiation on your behalf. A subsection of the application can enable the SslRequireCert option to negotiate the client certificate for those requests. For more information, see Configuration in the IIS documentation.
IIS automatically buffers any request body data up to a configured size limit before renegotiating. Requests that exceed the limit are rejected with a 413 response. This limit defaults to 48 KB and is configurable by setting the uploadReadAheadSize property.
HttpSys
HttpSys has two settings that control the client certificate negotiation and both should be set. The first is in the netsh.exe file under http add sslcert clientcertnegotiation=enable/disable. This flag indicates whether to negotiate the client certificate at the start of a connection. Set the value to disable for optional client certificates. For more information, see the http add sslcert parameter usage in the netsh docs.
The other setting is the ClientCertificateMethod property. When set to AllowRenegotation, the client certificate can be renegotiated during a request.
Note
The application should buffer or consume any request body data before attempting the renegotiation. Otherwise, the request might become unresponsive.
An application can first check the ClientCertificate property to see if the certificate is available. If it isn't available, ensure the request body is consumed before calling the GetClientCertificateAsync method to negotiate one. GetClientCertificateAsync can return a null certificate if the client declines to provide one.
Note
The behavior of the ClientCertificate property changed in .NET 6. For more information, see GitHub issue #466.
Kestrel
Kestrel controls client certificate negotiation with the ClientCertificateMode property.
.NET 6 and later provides the DelayCertificate option for the ClientCertificateMode property. When this option is set, an app can check the ClientCertificate property to see if the certificate is available. If it isn't available, ensure the request body is consumed before calling the GetClientCertificateAsync method to negotiate one. GetClientCertificateAsync can return a null certificate if the client declines to provide one.
Note
The application should buffer or consume any request body data before attempting the renegotiation. Otherwise, GetClientCertificateAsync might throw the exception, InvalidOperationException: Client stream needs to be drained before renegotiation.
If you programmatically configure the TLS settings per SNI host name, call the UseHttps overload (.NET 6 or later) that takes a TlsHandshakeCallbackOptions class object. This option controls client certificate renegotiation via the AllowDelayedClientCertificateNegotation property. For more information, see the ListenOptionsHttpsExtensions.UseHttps method.
Leave questions, comments, and other feedback on optional client certificates in the discussion thread for GitHub issue #18720.
Related content
ASP.NET Core