Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/reference/options.rst
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,9 @@ Mutual TLS
Specifies if MTLS support should be enabled. Defaults to ``false``.
* ``ClientCertificateAuthenticationScheme``
Specifies the name of the authentication handler for X.509 client certificates. Defaults to ``"Certificate"``.
This handler is required for MTLS client authentication: a client certificate is only accepted once this handler has authenticated it,
so it must be registered (typically with ``AddAuthentication().AddCertificate()``). If you change this option, register the handler under the same scheme name,
e.g. ``AddCertificate("MyCertificateScheme", ...)``.
* ``DomainName``
Specifies either the name of the sub-domain or full domain for running the MTLS endpoints (will use path-based endpoints if not set).
Use a simple string (e.g. "mtls") to set a sub-domain, use a full domain name (e.g. "identityserver-mtls.io") to set a full domain name.
Expand Down
54 changes: 49 additions & 5 deletions docs/topics/mtls.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,24 @@ Setting up MTLS involves a couple of steps.

Server setup
^^^^^^^^^^^^
It's the hosting layer's responsibility to do the actual validation of the client certificate.
Open.IdentityServer will then use that information to associate the certificate with a client and embed the certificate information in the access tokens.
The hosting layer (Kestrel, IIS, a reverse proxy) must be configured to request a client certificate and make it available to ASP.NET Core.

.. Important:: The hosting layer should validate client certificates, as a first line of defence. Configure your server or reverse proxy to reject any client
certificate that does not chain to a trusted CA, is expired, or has been revoked, **before** the request reaches Open.IdentityServer:

* Kestrel: do not use ``AllowAnyClientCertificate()``. Validate the certificate chain against your trusted CAs in ``ClientCertificateValidation`` and enable revocation checking.
* Reverse proxies (e.g. nginx): the proxy must validate the certificate (e.g. ``ssl_verify_client on``) and only forward certificates it has validated.
Forwarding a certificate that has not been validated has the same effect as accepting any certificate.
* Consider hosting the MTLS endpoints on a separate domain (``MutualTls.DomainName``) and not requesting client certificates on your main domain.

Note that rejecting untrusted certificates in the hosting layer also rejects self-signed certificates. If you rely on those (e.g. thumbprint-based secrets),
allow them in the hosting layer and restrict them with the certificate authentication handler's ``AllowedCertificateTypes``.

.. Warning:: Open.IdentityServer does not rely on the hosting layer alone. A client certificate is only accepted as a credential
after the ASP.NET Core certificate authentication handler (see below) has authenticated it. This handler is **required** for MTLS client authentication
and performs the chain, validity period and revocation checks. Validating in both places means a misconfiguration of one layer does not expose your clients.
Never rely on the secret matching (name or thumbprint) as proof that the certificate is trusted.


Depending which server you are using, those steps are different. Consult documentation for the type of server you are using for guidance on setting up this.

Expand Down Expand Up @@ -53,9 +69,33 @@ If you are using Nginx (which we found is the most flexible hosting option), you
};
});

Once, the certificate has been loaded, you also need to setup the authentication handler.
Once, the certificate has been loaded, you also need to setup the certificate authentication handler. This step is **required**: without it, clients cannot authenticate with a certificate.
Open.IdentityServer authenticates a client certificate with this handler on every endpoint that authenticates clients, and rejects the request if the handler does not accept the certificate.
In this scenario we want to support self-signed certificates, hence the ``CertificateType.All`` and no revocation checking.
These settings might be different in your environment
These settings might be different in your environment. For production, prefer the defaults (``CertificateTypes.Chained`` with revocation checking enabled) unless you specifically need self-signed certificates.

Custom scheme name
~~~~~~~~~~~~~~~~~~
By default the handler is registered as ``Certificate``, which matches the default value of ``options.MutualTls.ClientCertificateAuthenticationScheme``.
If you change that option, you must register the certificate authentication handler under the same scheme name:

.. code-block:: csharp

services.AddIdentityServer(options =>
{
options.MutualTls.Enabled = true;
options.MutualTls.ClientCertificateAuthenticationScheme = "MyCertificateScheme";
});

services.AddAuthentication()
.AddCertificate("MyCertificateScheme", options =>
{
options.AllowedCertificateTypes = CertificateTypes.Chained;
});

.. Warning:: If no handler is registered under the configured scheme name, MTLS client authentication fails with an
``InvalidOperationException`` ("No authentication handler is registered for the scheme ..."). The scheme must also be a certificate authentication
handler, since it reads the client certificate from the connection.

.. code-block:: csharp

Expand All @@ -69,7 +109,7 @@ These settings might be different in your environment
Open.IdentityServer setup
^^^^^^^^^^^^^^^^^^^^^^^^^
Next step is to enable MTLS in Open.IdentityServer. For that you need to specify the name of the certificate authentication handler you set-up in the last step (defaults to ``Certificate``),
and the MTLS hosting strategy.
and the MTLS hosting strategy. The handler named here must be registered (``AddCertificate``), otherwise MTLS client authentication fails.

In Open.IdentityServer, the mutual TLS endpoints, can be configured in three ways (assuming Open.IdentityServer is running on ``https://identityserver.com``:

Expand Down Expand Up @@ -106,6 +146,10 @@ Use the :ref:`Open.IdentityServer builder <refStartup>` to add the services to D

builder.AddMutualTlsSecretValidators();

.. Note:: The secret validators only match the certificate against the client's secret (name or thumbprint). They do not validate the certificate.
The certificate authentication handler configured in ``MutualTls.ClientCertificateAuthenticationScheme`` must be registered and must accept the certificate first.
Name-based secrets are only as trustworthy as that validation, because anyone can create a self-signed certificate with any subject name.
If you allow self-signed certificates (``CertificateTypes.All`` or ``SelfSigned``), prefer thumbprint-based secrets.
Finally, for the :ref:`client configuration <refClient>` add to the ``ClientSecrets`` collection a secret type of either ``SecretTypes.X509CertificateName``
if you wish to authenticate the client from the certificate distinguished name or ``SecretTypes.X509CertificateThumbprint`` if you wish to authenticate the client by certificate thumbprint.

Expand Down
3 changes: 2 additions & 1 deletion docs/topics/startup.rst
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ Additional services
Adds support for client authentication using JWT bearer assertions.

* ``AddMutualTlsSecretValidators``
Adds the X509 secret validators for mutual TLS.
Adds the X509 secret validators for mutual TLS. Requires the certificate authentication handler (``AddAuthentication().AddCertificate()``) to be registered;
client certificates are only accepted once that handler has authenticated them.

Caching
^^^^^^^
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,15 @@ public static IIdentityServerBuilder AddClientConfigurationValidator<T>(this IId
/// <summary>
/// Adds the X509 secret validators for mutual TLS.
/// </summary>
/// <remarks>
/// Client certificates are only accepted as credentials after the certificate authentication scheme
/// (<c>MutualTls.ClientCertificateAuthenticationScheme</c>, "Certificate" by default)
/// has authenticated them, on every endpoint that authenticates clients.
/// The scheme must be registered, usually with <c>services.AddAuthentication().AddCertificate()</c>,
/// otherwise client authentication with a certificate fails.
/// The scheme (not the secret validators) performs chain, validity and revocation checks, so configure its
/// <c>AllowedCertificateTypes</c> and revocation settings appropriately.
/// </remarks>
/// <param name="builder">The builder.</param>
/// <returns>The same <paramref name="builder"/> instance so that additional calls can be chained.</returns>
public static IIdentityServerBuilder AddMutualTlsSecretValidators(this IIdentityServerBuilder builder)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ public class MutualTlsOptions
public bool Enabled { get; set; }

/// <summary>
/// Specifies the name of the authentication handler for X.509 client certificates
/// Specifies the name of the authentication handler for X.509 client certificates.
/// This scheme is required for MTLS client authentication: a client certificate is only accepted as a
/// credential once this scheme has authenticated it. It is normally registered with
/// <c>AddAuthentication().AddCertificate()</c> and is responsible for validating the certificate chain,
/// validity period and revocation.
/// </summary>
public string ClientCertificateAuthenticationScheme { get; set; } = "Certificate";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ private static async Task ValidateAsync(IServiceProvider services, ILogger logge
var options = services.GetRequiredService<IdentityServerOptions>();
var schemes = services.GetRequiredService<IAuthenticationSchemeProvider>();

if (options.MutualTls.Enabled)
{
var certificateScheme = options.MutualTls.ClientCertificateAuthenticationScheme;
if (await schemes.GetSchemeAsync(certificateScheme) == null)
{
var error = $"Mutual TLS is enabled but the client certificate authentication scheme '{certificateScheme}' is not registered. Register it with 'AddAuthentication().AddCertificate(\"{certificateScheme}\", ...)' or set MutualTls.ClientCertificateAuthenticationScheme to the name of your certificate scheme.";
logger.LogCritical(error);
throw new InvalidOperationException(error);
}
}

if (await schemes.GetDefaultAuthenticateSchemeAsync() == null && options.Authentication.CookieAuthenticationScheme == null)
{
Expand Down
Comment thread
patchandthat marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Modified by Rock Solid Knowledge Ltd. Copyright in modifications 2026, Rock Solid Knowledge Ltd.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using System;
Expand All @@ -7,13 +8,17 @@
using Open.IdentityServer.Configuration;
using Open.IdentityServer.Extensions;
using Open.IdentityServer.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Open.IdentityServer.Validation;

/// <summary>
/// Parses secret according to MTLS spec
/// Parses secret according to MTLS spec.
/// The client certificate is only returned if the certificate authentication scheme
/// (<see cref="Configuration.MutualTlsOptions.ClientCertificateAuthenticationScheme"/>) accepts it,
/// so that scheme must be registered.
/// </summary>
public class MutualTlsSecretParser : ISecretParser
{
Expand Down Expand Up @@ -41,7 +46,8 @@ public MutualTlsSecretParser(IdentityServerOptions options, ILogger<MutualTlsSec
/// </summary>
/// <param name="context">The current HTTP context from which the client certificate and form body are read.</param>
/// <returns>
/// A <see cref="ParsedSecret"/> containing the client id and X.509 certificate when both are present and valid;
/// A <see cref="ParsedSecret"/> containing the client id and X.509 certificate when both are present and the
/// certificate has been accepted by the certificate authentication scheme;
/// otherwise <see langword="null"/>.
/// </returns>
public async Task<ParsedSecret> ParseAsync(HttpContext context)
Expand Down Expand Up @@ -76,6 +82,13 @@ public async Task<ParsedSecret> ParseAsync(HttpContext context)
_logger.LogDebug("Client certificate not present");
return null;
}

var authResult = await context.AuthenticateAsync(_options.MutualTls.ClientCertificateAuthenticationScheme);
if (!authResult.Succeeded)
{
_logger.LogWarning("Client certificate rejected by authentication scheme: {error}", authResult.Failure?.Message);
return null;
}

return new ParsedSecret
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,58 @@ public void UseIdentityServer_WithCreateAccountUrlButCreateAccountReturnUrlParam
.WithMessage("CreateAccountReturnUrlParameter is not configured");
}

[Fact]
public void UseIdentityServer_WithMutualTlsEnabledAndSchemeMissing_ShouldThrowInvalidOperationException()
{
var options = new IdentityServerOptions();
options.MutualTls.Enabled = true;

var app = BuildAppBuilder(identityServerOptions: options);

Action act = () => app.UseIdentityServer(CreateNoOpMiddlewareOptions());

act.Should().Throw<InvalidOperationException>()
.WithMessage("*'Certificate' is not registered*");
}

[Fact]
public void UseIdentityServer_WithMutualTlsEnabledAndSchemeRegistered_ShouldNotThrow()
{
var options = new IdentityServerOptions();
options.MutualTls.Enabled = true;

var app = BuildAppBuilder(identityServerOptions: options, certificateScheme: "Certificate");

Action act = () => app.UseIdentityServer(CreateNoOpMiddlewareOptions());

act.Should().NotThrow();
}

[Fact]
public void UseIdentityServer_WithMutualTlsEnabledAndCustomSchemeNotRegistered_ShouldThrowInvalidOperationException()
{
var options = new IdentityServerOptions();
options.MutualTls.Enabled = true;
options.MutualTls.ClientCertificateAuthenticationScheme = "MyCerts";

var app = BuildAppBuilder(identityServerOptions: options, certificateScheme: "Certificate");

Action act = () => app.UseIdentityServer(CreateNoOpMiddlewareOptions());

act.Should().Throw<InvalidOperationException>()
.WithMessage("*'MyCerts' is not registered*");
}

[Fact]
public void UseIdentityServer_WithMutualTlsDisabledAndSchemeMissing_ShouldNotThrow()
{
var app = BuildAppBuilder();

Action act = () => app.UseIdentityServer(CreateNoOpMiddlewareOptions());

act.Should().NotThrow();
}

private static IdentityServerMiddlewareOptions CreateNoOpMiddlewareOptions()
=> new()
{
Expand All @@ -232,7 +284,8 @@ private static IApplicationBuilder BuildAppBuilder(
bool registerPersistedGrantStore = true,
bool registerClientStore = true,
bool registerResourceStore = true,
IdentityServerOptions identityServerOptions = null)
IdentityServerOptions identityServerOptions = null,
string certificateScheme = null)
{
var services = new ServiceCollection();

Expand All @@ -241,7 +294,13 @@ private static IApplicationBuilder BuildAppBuilder(
services.AddSingleton<Microsoft.Extensions.Logging.ILoggerFactory, Microsoft.Extensions.Logging.LoggerFactory>();
}

services.AddAuthenticationCore();
services.AddAuthenticationCore(o =>
{
if (certificateScheme != null)
{
o.AddScheme(certificateScheme, b => b.HandlerType = typeof(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler));
}
});
services.AddCors();

services.AddSingleton(identityServerOptions ?? new IdentityServerOptions());
Expand Down
Loading
Loading