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
Original file line number Diff line number Diff line change
Expand Up @@ -216,15 +216,15 @@ public async Task<TokenRequestValidationResult> ValidateRequestAsync(TokenReques

private async Task<TokenRequestValidationResult> ValidateProofToken(TokenRequestValidationContext context)
{
// can't allow both both at once
if (context.ClientCertificate != null && context.DPoPProofToken.IsPresent())
{
LogError("Only one confirmation mechanism is allowed at a time.");
return Invalid(OidcConstants.TokenErrors.InvalidRequest, "Only one confirmation mechanism is allowed at a time");
}

// mTLS client cert processing
if (context.ClientCertificate != null)
//
// If both a dpop proof and client certificate are present, we use the
// proof token for sender-constraining the token. DPoP takes precedence
// because that's the only sensible interpretation of the client's
// request. DPoP can only be used for sender constraining the token,
// but client certificates can also be used as client authentication.
if (context.ClientCertificate != null && context.DPoPProofToken.IsMissing())
{
if (_options.MutualTls.AlwaysEmitConfirmationClaim && _validatedRequest.Confirmation.IsMissing())
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System.Net;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using Duende.IdentityModel.Client;
using Duende.IdentityServer;
Expand All @@ -17,6 +18,7 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
Expand All @@ -39,6 +41,7 @@ public class IdentityServerPipeline
public const string AuthorizeEndpoint = BaseUrl + "/connect/authorize";
public const string BackchannelAuthenticationEndpoint = BaseUrl + "/connect/ciba";
public const string TokenEndpoint = BaseUrl + "/connect/token";
public const string TokenMtlsEndpoint = BaseUrl + "/connect/mtls/token";
public const string RevocationEndpoint = BaseUrl + "/connect/revocation";
public const string UserInfoEndpoint = BaseUrl + "/connect/userinfo";
public const string IntrospectionEndpoint = BaseUrl + "/connect/introspect";
Expand All @@ -47,6 +50,7 @@ public class IdentityServerPipeline
public const string CheckSessionEndpoint = BaseUrl + "/connect/checksession";
public const string ParEndpoint = BaseUrl + "/connect/par";


public const string FederatedSignOutPath = "/signout-oidc";
public const string FederatedSignOutUrl = BaseUrl + FederatedSignOutPath;

Expand All @@ -63,6 +67,10 @@ public class IdentityServerPipeline
public BrowserClient BrowserClient { get; set; }
public HttpClient BackChannelClient { get; set; }

// mTLS support
public X509Certificate2 ClientCertificate { get; set; }
public HttpClient MtlsBackChannelClient { get; set; }

public MockMessageHandler BackChannelMessageHandler { get; set; } = new MockMessageHandler();
public MockMessageHandler JwtRequestMessageHandler { get; set; } = new MockMessageHandler();

Expand Down Expand Up @@ -107,6 +115,9 @@ public void Initialize(string basePath = null, bool enableLogging = false)

BrowserClient = new BrowserClient(new BrowserHandler(Handler));
BackChannelClient = new HttpClient(Handler);

// Initialize mTLS client (will be null until a certificate is set)
UpdateMtlsClient();
}

public void ConfigureServices(IServiceCollection services)
Expand All @@ -120,6 +131,11 @@ public void ConfigureServices(IServiceCollection services)
scheme.DisplayName = "External";
scheme.HandlerType = typeof(MockExternalAuthenticationHandler);
});
opts.AddScheme("Certificate", scheme =>
{
scheme.DisplayName = "Certificate";
scheme.HandlerType = typeof(MockCertificateAuthenticationHandler);
});
});
services.AddTransient<MockExternalAuthenticationHandler>(svcs =>
{
Expand All @@ -143,14 +159,17 @@ public void ConfigureServices(IServiceCollection services)
};
options.KeyManagement.Enabled = false;

options.MutualTls.Enabled = true;

Options = options;
})
.AddInMemoryClients(Clients)
.AddInMemoryIdentityResources(IdentityScopes)
.AddInMemoryApiResources(ApiResources)
.AddInMemoryApiScopes(ApiScopes)
.AddTestUsers(Users)
.AddDeveloperSigningCredential(persistKey: false);
.AddDeveloperSigningCredential(persistKey: false)
.AddMutualTlsSecretValidators();

services.AddHttpClient(IdentityServerConstants.HttpClients.BackChannelLogoutHttpClient)
.AddHttpMessageHandler(() => BackChannelMessageHandler);
Expand All @@ -167,6 +186,9 @@ public void ConfigureApp(IApplicationBuilder app)

OnPreConfigure(app);

// Add mTLS test middleware before IdentityServer middleware
app.UseMiddleware<MtlsTestMiddleware>();

app.UseIdentityServer();

// UI endpoints
Expand Down Expand Up @@ -463,6 +485,40 @@ public string CreateAuthorizeUrl(
public T Resolve<T>() =>
// create throw-away scope
ApplicationServices.CreateScope().ServiceProvider.GetRequiredService<T>();

/* mTLS helpers */
public void SetClientCertificate(X509Certificate2 certificate)
{
ClientCertificate = certificate;
UpdateMtlsClient();
}

private void UpdateMtlsClient()
{
MtlsBackChannelClient?.Dispose();

if (ClientCertificate != null)
{
var mtlsHandler = new MtlsMessageHandler(Handler, ClientCertificate);
MtlsBackChannelClient = new HttpClient(mtlsHandler)
{
BaseAddress = new Uri(BaseUrl)
};
}
else
{
MtlsBackChannelClient = null;
}
}

public HttpClient GetMtlsClient()
{
if (MtlsBackChannelClient == null)
{
throw new InvalidOperationException("No client certificate has been set. Call SetClientCertificate() first.");
}
return MtlsBackChannelClient;
}
}

public class MockMessageHandler : DelegatingHandler
Expand Down Expand Up @@ -522,3 +578,30 @@ public async Task<bool> HandleRequestAsync()

public Task SignOutAsync(AuthenticationProperties properties) => Task.CompletedTask;
}

public class MockCertificateAuthenticationHandler : IAuthenticationHandler
{
private HttpContext _context;
private string _scheme;

public Task<AuthenticateResult> AuthenticateAsync()
{
if (_context?.Features.Get<ITlsConnectionFeature>() is { ClientCertificate: not null })
{
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(
new ClaimsPrincipal(new ClaimsIdentity([])), _scheme)));
}
return Task.FromResult(AuthenticateResult.Fail("No client certificate set."));
}

public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
_scheme = scheme.Name;
_context = context;
return Task.CompletedTask;
}

public Task ChallengeAsync(AuthenticationProperties properties) => Task.CompletedTask;

public Task ForbidAsync(AuthenticationProperties properties) => Task.CompletedTask;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.


using System.Security.Cryptography.X509Certificates;

namespace IntegrationTests.Common;

/// <summary>
/// Message handler that injects a client certificate into the HTTP request for testing mTLS scenarios
/// </summary>
public class MtlsMessageHandler : DelegatingHandler
{
private readonly X509Certificate2 _clientCertificate;

public MtlsMessageHandler(HttpMessageHandler innerHandler, X509Certificate2 clientCertificate)
: base(innerHandler) => _clientCertificate = clientCertificate;

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Add the client certificate as a base64 encoded header for the test middleware to pick up
if (_clientCertificate != null)
{
var certBytes = _clientCertificate.Export(X509ContentType.Cert);
var certBase64 = Convert.ToBase64String(certBytes);
request.Headers.Add("X-Test-Client-Certificate", certBase64);
}

return await base.SendAsync(request, cancellationToken);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.


using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;

namespace IntegrationTests.Common;

/// <summary>
/// Middleware for testing mTLS scenarios by injecting client certificates from request properties
/// </summary>
public class MtlsTestMiddleware
{
private readonly RequestDelegate _next;

public MtlsTestMiddleware(RequestDelegate next) => _next = next;

public async Task InvokeAsync(HttpContext context)
{
// Check if the request has a client certificate in its properties
if (context.Request.HttpContext.Features.Get<IHttpRequestFeature>() is IHttpRequestFeature requestFeature)
{
// Try to get the certificate from request properties (injected by MtlsMessageHandler)
if (context.Features.Get<X509Certificate2>() == null)
{
// Look for certificate in request headers or properties
// This is a simplified approach for testing - in real scenarios the certificate
// would be part of the TLS handshake
var cert = GetClientCertificateFromRequest(context);
if (cert != null)
{
// Create a custom feature to hold the client certificate
var tlsFeature = new TlsConnectionFeature { ClientCertificate = cert };
context.Features.Set<ITlsConnectionFeature>(tlsFeature);
}
}
}

await _next(context);
}

private static X509Certificate2 GetClientCertificateFromRequest(HttpContext context)
{
// For testing purposes, we'll try to get the certificate from a custom header
// This simulates what would normally be provided by the TLS layer
if (context.Request.Headers.TryGetValue("X-Test-Client-Certificate", out var certHeader))
{
try
{
var certBytes = Convert.FromBase64String(certHeader.First());
#pragma warning disable SYSLIB0057 // Type or member is obsolete
return new X509Certificate2(certBytes);
#pragma warning restore SYSLIB0057 // Type or member is obsolete
}
catch
{
// Ignore invalid certificate data
}
}

return null;
}
}

/// <summary>
/// Custom implementation of ITlsConnectionFeature for testing
/// </summary>
public class TlsConnectionFeature : ITlsConnectionFeature
{
public X509Certificate2 ClientCertificate { get; set; }

public Task<X509Certificate2> GetClientCertificateAsync(CancellationToken cancellationToken)
=> Task.FromResult(ClientCertificate);
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public async Task valid_dpop_request_should_return_bound_access_token()
[Trait("Category", Category)]
public async Task valid_dpop_request_with_unusual_but_valid_proof_token_should_return_bound_access_token()
{
// The point here is to have an array in the payload, to exercise
// The point here is to have an array in the payload, to exercise
// the json serialization
Payload.Add("key_ops", new string[] { "sign", "verify" });
var request = CreateClientCredentialsTokenRequest();
Expand Down Expand Up @@ -448,6 +448,59 @@ public async Task all_supported_signing_algorithms_should_work(string alg, KeyTy
var jkt = GetJKTFromAccessToken(response);
jkt.ShouldBe(JKT);
}

[Fact]
[Trait("Category", Category)]
public async Task mtls_and_dpop_request_should_succeed()
{
var clientId = "mtls_dpop_client";
var clientCert = TestCert.Load();

// Add a client that requires mTLS and supports DPoP
var client = new Client
{
ClientId = clientId,
ClientSecrets =
{
new Secret
{
Type = IdentityServerConstants.SecretTypes.X509CertificateThumbprint,
Value = clientCert.Thumbprint
}
},
AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes = { "scope1" },
RequireDPoP = true
};

Pipeline.Clients.Add(client);
Pipeline.Initialize();

// Set the client certificate in the pipeline
Pipeline.SetClientCertificate(clientCert);

// Act - Make a client credentials request using mTLS and DPoP
var tokenClient = Pipeline.GetMtlsClient();

var formParams = new Dictionary<string, string>
{
{ "grant_type", "client_credentials" },
{ "client_id", clientId },
{ "scope", "scope1" }
};

var form = new FormUrlEncodedContent(formParams);
tokenClient.DefaultRequestHeaders.Add("DPoP", CreateDPoPProofToken());

var response = await tokenClient.PostAsync(IdentityServerPipeline.TokenMtlsEndpoint, form);

// Assert
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);

var json = await response.Content.ReadAsStringAsync();
json.ShouldContain("access_token");
json.ShouldContain("\"token_type\":\"DPoP\"");
}
}

public class ParModes : TheoryData<ParMode>
Expand Down
Loading