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 @@ -13,6 +13,8 @@ namespace Microsoft.AspNetCore.Authentication.Certificate;

internal sealed class CertificateAuthenticationHandler : AuthenticationHandler<CertificateAuthenticationOptions>
{
internal const string CertificateSchemeCacheKeyItem = "__CertificateAuthScheme";

private static readonly Oid ClientCertificateOid = new Oid("1.3.6.1.5.5.7.3.2");
private ICertificateValidationCache? _cache;

Expand Down Expand Up @@ -67,6 +69,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()

if (_cache != null)
{
Context.Items[CertificateSchemeCacheKeyItem] = Scheme.Name;
var cacheHit = _cache.Get(Context, clientCertificate);
if (cacheHit != null)
Comment on lines 70 to 74
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,14 @@ public CertificateValidationCache(IOptions<CertificateValidationCacheOptions> op
/// <param name="certificate">The certificate.</param>
/// <returns>the <see cref="AuthenticateResult"/></returns>
public AuthenticateResult? Get(HttpContext context, X509Certificate2 certificate)
=> _cache.Get<AuthenticateResult>(ComputeKey(certificate))?.Clone();
{
var key = ComputeKey(context, certificate);
if (key is null)
{
return null;
}
return _cache.Get<AuthenticateResult>(key)?.Clone();
}
Comment on lines 41 to +49

/// <summary>
/// Store a <see cref="AuthenticateResult"/> for the connection and certificate
Expand All @@ -49,21 +56,34 @@ public CertificateValidationCache(IOptions<CertificateValidationCacheOptions> op
/// <param name="result">the <see cref="AuthenticateResult"/></param>
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();
if (notAfter < absoluteExpiration)
{
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)}";
Comment on lines +78 to +83
}
return null;
}

private sealed class CachingClock : Extensions.Internal.ISystemClock
{
Expand Down
125 changes: 125 additions & 0 deletions src/Security/Authentication/test/CertificateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -941,5 +941,130 @@ private static async Task<IHost> 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);
}
}

Loading