From 0226db77ed464763150dee4de2202be7dc80b272 Mon Sep 17 00:00:00 2001 From: Jo Stevens Date: Tue, 17 Nov 2026 16:28:56 +0000 Subject: [PATCH 1/2] fix: MTLS validation when using non-MTLS path --- docs/reference/options.rst | 3 + docs/topics/mtls.rst | 54 ++++++- docs/topics/startup.rst | 3 +- .../BuilderExtensions/Additional.cs | 9 ++ .../Options/MtlsOptions.cs | 6 +- ...ntityServerApplicationBuilderExtensions.cs | 10 ++ .../Default/MutualTlsSecretParser.cs | 16 ++- ...ServerApplicationBuilderExtensionsTests.cs | 63 ++++++++- .../Secrets/MutualTlsSecretParsing.cs | 132 ++++++++++++++++++ 9 files changed, 285 insertions(+), 11 deletions(-) create mode 100644 src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Validation/Secrets/MutualTlsSecretParsing.cs diff --git a/docs/reference/options.rst b/docs/reference/options.rst index 9dfb8e2ec..b3a846142 100644 --- a/docs/reference/options.rst +++ b/docs/reference/options.rst @@ -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. diff --git a/docs/topics/mtls.rst b/docs/topics/mtls.rst index e2fc567cb..2247bbd46 100644 --- a/docs/topics/mtls.rst +++ b/docs/topics/mtls.rst @@ -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. @@ -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 @@ -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``: @@ -106,6 +146,10 @@ Use the :ref:`Open.IdentityServer builder ` 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 ` 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. diff --git a/docs/topics/startup.rst b/docs/topics/startup.rst index 12105fa7d..9c433dbe4 100644 --- a/docs/topics/startup.rst +++ b/docs/topics/startup.rst @@ -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 ^^^^^^^ diff --git a/src/Open.IdentityServer/src/Configuration/DependencyInjection/BuilderExtensions/Additional.cs b/src/Open.IdentityServer/src/Configuration/DependencyInjection/BuilderExtensions/Additional.cs index 6b4e0e41f..e64d75986 100644 --- a/src/Open.IdentityServer/src/Configuration/DependencyInjection/BuilderExtensions/Additional.cs +++ b/src/Open.IdentityServer/src/Configuration/DependencyInjection/BuilderExtensions/Additional.cs @@ -335,6 +335,15 @@ public static IIdentityServerBuilder AddClientConfigurationValidator(this IId /// /// Adds the X509 secret validators for mutual TLS. /// + /// + /// Client certificates are only accepted as credentials after the certificate authentication scheme + /// (MutualTls.ClientCertificateAuthenticationScheme, "Certificate" by default) + /// has authenticated them, on every endpoint that authenticates clients. + /// The scheme must be registered, usually with services.AddAuthentication().AddCertificate(), + /// otherwise client authentication with a certificate fails. + /// The scheme (not the secret validators) performs chain, validity and revocation checks, so configure its + /// AllowedCertificateTypes and revocation settings appropriately. + /// /// The builder. /// The same instance so that additional calls can be chained. public static IIdentityServerBuilder AddMutualTlsSecretValidators(this IIdentityServerBuilder builder) diff --git a/src/Open.IdentityServer/src/Configuration/DependencyInjection/Options/MtlsOptions.cs b/src/Open.IdentityServer/src/Configuration/DependencyInjection/Options/MtlsOptions.cs index 535d67cac..3dd83b766 100644 --- a/src/Open.IdentityServer/src/Configuration/DependencyInjection/Options/MtlsOptions.cs +++ b/src/Open.IdentityServer/src/Configuration/DependencyInjection/Options/MtlsOptions.cs @@ -15,7 +15,11 @@ public class MutualTlsOptions public bool Enabled { get; set; } /// - /// 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 + /// AddAuthentication().AddCertificate() and is responsible for validating the certificate chain, + /// validity period and revocation. /// public string ClientCertificateAuthenticationScheme { get; set; } = "Certificate"; diff --git a/src/Open.IdentityServer/src/Configuration/IdentityServerApplicationBuilderExtensions.cs b/src/Open.IdentityServer/src/Configuration/IdentityServerApplicationBuilderExtensions.cs index 348d04ebd..716e22bce 100644 --- a/src/Open.IdentityServer/src/Configuration/IdentityServerApplicationBuilderExtensions.cs +++ b/src/Open.IdentityServer/src/Configuration/IdentityServerApplicationBuilderExtensions.cs @@ -86,6 +86,16 @@ private static async Task ValidateAsync(IServiceProvider services, ILogger logge var options = services.GetRequiredService(); var schemes = services.GetRequiredService(); + 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) { diff --git a/src/Open.IdentityServer/src/Validation/Default/MutualTlsSecretParser.cs b/src/Open.IdentityServer/src/Validation/Default/MutualTlsSecretParser.cs index 9f321ed4d..08cd08eea 100644 --- a/src/Open.IdentityServer/src/Validation/Default/MutualTlsSecretParser.cs +++ b/src/Open.IdentityServer/src/Validation/Default/MutualTlsSecretParser.cs @@ -7,13 +7,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; /// -/// Parses secret according to MTLS spec +/// Parses secret according to MTLS spec. +/// The client certificate is only returned if the certificate authentication scheme +/// () accepts it, +/// so that scheme must be registered. /// public class MutualTlsSecretParser : ISecretParser { @@ -41,7 +45,8 @@ public MutualTlsSecretParser(IdentityServerOptions options, ILogger /// The current HTTP context from which the client certificate and form body are read. /// - /// A containing the client id and X.509 certificate when both are present and valid; + /// A containing the client id and X.509 certificate when both are present and the + /// certificate has been accepted by the certificate authentication scheme; /// otherwise . /// public async Task ParseAsync(HttpContext context) @@ -76,6 +81,13 @@ public async Task 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 { diff --git a/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Configuration/IdentityServerApplicationBuilderExtensionsTests.cs b/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Configuration/IdentityServerApplicationBuilderExtensionsTests.cs index 1c1966c29..12388dbb1 100644 --- a/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Configuration/IdentityServerApplicationBuilderExtensionsTests.cs +++ b/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Configuration/IdentityServerApplicationBuilderExtensionsTests.cs @@ -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() + .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() + .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() { @@ -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(); @@ -241,7 +294,13 @@ private static IApplicationBuilder BuildAppBuilder( services.AddSingleton(); } - 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()); diff --git a/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Validation/Secrets/MutualTlsSecretParsing.cs b/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Validation/Secrets/MutualTlsSecretParsing.cs new file mode 100644 index 000000000..383d44c8d --- /dev/null +++ b/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Validation/Secrets/MutualTlsSecretParsing.cs @@ -0,0 +1,132 @@ +// Copyright (c) 2026, Rock Solid Knowledge Ltd +// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. + +using System; +using System.IO; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading.Tasks; +using AwesomeAssertions; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Open.IdentityServer.Configuration; +using Open.IdentityServer.Validation; +using Xunit; + +namespace Open.IdentityServer.UnitTests.Validation.Secrets; + +public class MutualTlsSecretParsing +{ + private const string Category = "Secrets - Mutual TLS Secret Parsing"; + + private readonly IdentityServerOptions _options = new(); + private readonly Mock _authenticationService = new(); + private readonly MutualTlsSecretParser _parser; + + public MutualTlsSecretParsing() + { + _parser = new MutualTlsSecretParser(_options, NullLogger.Instance); + } + + [Fact] + [Trait("Category", Category)] + public async Task Certificate_accepted_by_scheme_should_return_secret() + { + SetupAuthentication(AuthenticateResult.Success( + new AuthenticationTicket(new System.Security.Claims.ClaimsPrincipal(), "Certificate"))); + using var cert = CreateCertificate(); + + var secret = await _parser.ParseAsync(CreateContext(cert)); + + secret.Should().NotBeNull(); + secret.Id.Should().Be("client"); + secret.Type.Should().Be(IdentityServerConstants.ParsedSecretTypes.X509Certificate); + secret.Credential.Should().BeSameAs(cert); + _authenticationService.Verify( + x => x.AuthenticateAsync(It.IsAny(), "Certificate"), Times.Once); + } + + [Fact] + [Trait("Category", Category)] + public async Task Certificate_rejected_by_scheme_should_return_null() + { + SetupAuthentication(AuthenticateResult.Fail("untrusted")); + using var cert = CreateCertificate(); + + var secret = await _parser.ParseAsync(CreateContext(cert)); + + secret.Should().BeNull(); + _authenticationService.Verify( + x => x.AuthenticateAsync(It.IsAny(), "Certificate"), Times.Once); + } + + [Fact] + [Trait("Category", Category)] + public async Task Custom_scheme_name_should_be_used_for_authentication() + { + _options.MutualTls.ClientCertificateAuthenticationScheme = "MyCerts"; + SetupAuthentication(AuthenticateResult.Fail("untrusted"), "MyCerts"); + using var cert = CreateCertificate(); + + await _parser.ParseAsync(CreateContext(cert)); + + _authenticationService.Verify( + x => x.AuthenticateAsync(It.IsAny(), "MyCerts"), Times.Once); + _authenticationService.Verify( + x => x.AuthenticateAsync(It.IsAny(), "Certificate"), Times.Never); + } + + [Fact] + [Trait("Category", Category)] + public async Task No_certificate_should_not_call_authentication() + { + var secret = await _parser.ParseAsync(CreateContext(null)); + + secret.Should().BeNull(); + _authenticationService.Verify( + x => x.AuthenticateAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + [Trait("Category", Category)] + public async Task No_client_id_should_not_call_authentication() + { + using var cert = CreateCertificate(); + + var secret = await _parser.ParseAsync(CreateContext(cert, body: "foo=bar")); + + secret.Should().BeNull(); + _authenticationService.Verify( + x => x.AuthenticateAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + private void SetupAuthentication(AuthenticateResult result, string scheme = "Certificate") + { + _authenticationService + .Setup(x => x.AuthenticateAsync(It.IsAny(), scheme)) + .ReturnsAsync(result); + } + + private DefaultHttpContext CreateContext(X509Certificate2 cert, string body = "client_id=client") + { + var services = new ServiceCollection(); + services.AddSingleton(_authenticationService.Object); + + var context = new DefaultHttpContext { RequestServices = services.BuildServiceProvider() }; + context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); + context.Request.ContentType = "application/x-www-form-urlencoded"; + context.Connection.ClientCertificate = cert; + return context; + } + + private static X509Certificate2 CreateCertificate() + { + using var rsa = RSA.Create(2048); + var request = new CertificateRequest("CN=client", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + } +} From 1d8d2f7c37f59d4a2eb85037b579093967d3e24d Mon Sep 17 00:00:00 2001 From: Patrick Allwood Date: Tue, 17 Nov 2026 17:32:17 +0000 Subject: [PATCH 2/2] chore: header update --- .../src/Validation/Default/MutualTlsSecretParser.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Open.IdentityServer/src/Validation/Default/MutualTlsSecretParser.cs b/src/Open.IdentityServer/src/Validation/Default/MutualTlsSecretParser.cs index 08cd08eea..3585de063 100644 --- a/src/Open.IdentityServer/src/Validation/Default/MutualTlsSecretParser.cs +++ b/src/Open.IdentityServer/src/Validation/Default/MutualTlsSecretParser.cs @@ -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;