From e96171c33936a6e37c4c7a136ac58c86b51e3745 Mon Sep 17 00:00:00 2001 From: Dmitrii Korolev Date: Tue, 14 Apr 2026 16:58:29 +0000 Subject: [PATCH] Merged PR 60023: [release/9.0] fix(Security/Authentication): include scheme in certificate cache Storing scheme as a string in `HttpContext.Items` under `__CertificateAuthScheme`, which is used as part of cache key now. (cherry picked from commit b0b333dabed23ddbe528fd82815973735295b651) --- .../src/CertificateAuthenticationHandler.cs | 3 + .../src/CertificateValidationCache.cs | 28 +++- .../Authentication/test/CertificateTests.cs | 125 ++++++++++++++++++ 3 files changed, 152 insertions(+), 4 deletions(-) diff --git a/src/Security/Authentication/Certificate/src/CertificateAuthenticationHandler.cs b/src/Security/Authentication/Certificate/src/CertificateAuthenticationHandler.cs index de74d6e5bf7c..98d647bc558b 100644 --- a/src/Security/Authentication/Certificate/src/CertificateAuthenticationHandler.cs +++ b/src/Security/Authentication/Certificate/src/CertificateAuthenticationHandler.cs @@ -13,6 +13,8 @@ namespace Microsoft.AspNetCore.Authentication.Certificate; internal sealed class CertificateAuthenticationHandler : AuthenticationHandler { + internal const string CertificateSchemeCacheKeyItem = "__CertificateAuthScheme"; + private static readonly Oid ClientCertificateOid = new Oid("1.3.6.1.5.5.7.3.2"); private ICertificateValidationCache? _cache; @@ -67,6 +69,7 @@ protected override async Task HandleAuthenticateAsync() if (_cache != null) { + Context.Items[CertificateSchemeCacheKeyItem] = Scheme.Name; var cacheHit = _cache.Get(Context, clientCertificate); if (cacheHit != null) { diff --git a/src/Security/Authentication/Certificate/src/CertificateValidationCache.cs b/src/Security/Authentication/Certificate/src/CertificateValidationCache.cs index 432a0d2e47bb..27252d8506f0 100644 --- a/src/Security/Authentication/Certificate/src/CertificateValidationCache.cs +++ b/src/Security/Authentication/Certificate/src/CertificateValidationCache.cs @@ -39,7 +39,14 @@ public CertificateValidationCache(IOptions op /// The certificate. /// the public AuthenticateResult? Get(HttpContext context, X509Certificate2 certificate) - => _cache.Get(ComputeKey(certificate))?.Clone(); + { + var key = ComputeKey(context, certificate); + if (key is null) + { + return null; + } + return _cache.Get(key)?.Clone(); + } /// /// Store a for the connection and certificate @@ -49,6 +56,12 @@ public CertificateValidationCache(IOptions op /// the public void Put(HttpContext context, X509Certificate2 certificate, AuthenticateResult result) { + var key = ComputeKey(context, certificate); + if (key is null) + { + return; + } + // Never cache longer than 30 minutes var absoluteExpiration = _timeProvider.GetUtcNow().Add(TimeSpan.FromMinutes(30)); var notAfter = certificate.NotAfter.ToUniversalTime(); @@ -56,14 +69,21 @@ public void Put(HttpContext context, X509Certificate2 certificate, AuthenticateR { absoluteExpiration = notAfter; } - _cache.Set(ComputeKey(certificate), result.Clone(), new MemoryCacheEntryOptions() + _cache.Set(key, result.Clone(), new MemoryCacheEntryOptions() .SetSize(1) .SetSlidingExpiration(_options.CacheEntryExpiration) .SetAbsoluteExpiration(absoluteExpiration)); } - private static string ComputeKey(X509Certificate2 certificate) - => certificate.GetCertHashString(HashAlgorithmName.SHA256); + private static string? ComputeKey(HttpContext context, X509Certificate2 certificate) + { + if (context.Items.TryGetValue(CertificateAuthenticationHandler.CertificateSchemeCacheKeyItem, out var schemeObj) + && schemeObj is string schemeName) + { + return $"{schemeName}:{certificate.GetCertHashString(HashAlgorithmName.SHA256)}"; + } + return null; + } private sealed class CachingClock : Extensions.Internal.ISystemClock { diff --git a/src/Security/Authentication/test/CertificateTests.cs b/src/Security/Authentication/test/CertificateTests.cs index ba8e163539b3..4dec49737423 100644 --- a/src/Security/Authentication/test/CertificateTests.cs +++ b/src/Security/Authentication/test/CertificateTests.cs @@ -941,5 +941,130 @@ private static async Task CreateHost( return Task.CompletedTask; } }; + + [Fact] + public async Task VerifyCacheIsIsolatedAcrossSchemes() + { + var scheme1ValidationCount = 0; + var scheme2ValidationCount = 0; + + using var host = new HostBuilder() + .ConfigureWebHost(builder => + builder.UseTestServer() + .Configure(app => + { + app.Use((context, next) => + { + context.Connection.ClientCertificate = Certificates.SelfSignedValidWithNoEku; + return next(context); + }); + + app.UseAuthentication(); + + app.Run(async context => + { + var schemeName = context.Request.Query["scheme"].ToString(); + var result = await context.AuthenticateAsync(schemeName); + + if (result.Succeeded) + { + context.Response.StatusCode = (int)HttpStatusCode.OK; + context.Response.ContentType = "text/plain"; + await context.Response.WriteAsync("Authenticated"); + } + else + { + context.Response.StatusCode = (int)HttpStatusCode.Forbidden; + context.Response.ContentType = "text/plain"; + await context.Response.WriteAsync("Denied"); + } + }); + }) + .ConfigureServices(services => + { + services.AddAuthentication() + .AddCertificate("scheme1", options => + { + options.AllowedCertificateTypes = CertificateTypes.SelfSigned; + options.Events = new CertificateAuthenticationEvents + { + OnCertificateValidated = context => + { + scheme1ValidationCount++; + context.Principal = new ClaimsPrincipal( + new ClaimsIdentity( + [new Claim(ClaimTypes.Name, "scheme1User")], + context.Scheme.Name)); + context.Success(); + return Task.CompletedTask; + } + }; + }) + .AddCertificate("scheme2", options => + { + options.AllowedCertificateTypes = CertificateTypes.SelfSigned; + options.Events = new CertificateAuthenticationEvents + { + OnCertificateValidated = context => + { + scheme2ValidationCount++; + context.Fail("Certificate does not meet scheme2 requirements"); + return Task.CompletedTask; + } + }; + }) + .AddCertificateCache(); + })) + .Build(); + + await host.StartAsync(); + + using var server = host.GetTestServer(); + var client = server.CreateClient(); + + // 1. Authenticate with the scheme1 — should succeed and cache + var response1 = await client.GetAsync("https://example.com/?scheme=scheme1"); + Assert.Equal(HttpStatusCode.OK, response1.StatusCode); + Assert.Equal(1, scheme1ValidationCount); + + // 2. Authenticate with the scheme2 — must NOT reuse the scheme1's cached success + var response2 = await client.GetAsync("https://example.com/?scheme=scheme2"); + Assert.Equal(HttpStatusCode.Forbidden, response2.StatusCode); + Assert.Equal(1, scheme2ValidationCount); + + // 3. Authenticate with the scheme1 again — should use the cache (no re-validation) + var response3 = await client.GetAsync("https://example.com/?scheme=scheme1"); + Assert.Equal(HttpStatusCode.OK, response3.StatusCode); + Assert.Equal(1, scheme1ValidationCount); // Still 1 — served from cache + } + + [Fact] + public void VerifyCacheNoOpsWithoutSchemeInHttpContextItems() + { + var cache = new CertificateValidationCache(Options.Create(new CertificateValidationCacheOptions())); + var certificate = Certificates.SelfSignedValidWithNoEku; + + var httpContext = new DefaultHttpContext(); + // Do NOT set httpContext.Items[CertificateAuthenticationHandler.CertificateSchemeCacheKeyItem] + + // Put should no-op (no scheme = no cache key) + var successResult = AuthenticateResult.Success( + new AuthenticationTicket( + new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "test") }, "test")), + "test")); + cache.Put(httpContext, certificate, successResult); + + // Get should return null even after Put + var cached = cache.Get(httpContext, certificate); + Assert.Null(cached); + + // Now set the scheme item — Put and Get should work + httpContext.Items[CertificateAuthenticationHandler.CertificateSchemeCacheKeyItem] = "MyScheme"; + cache.Put(httpContext, certificate, successResult); + + var cachedWithScheme = cache.Get(httpContext, certificate); + Assert.NotNull(cachedWithScheme); + Assert.True(cachedWithScheme.Succeeded); + } }