Created
March 18, 2025 17:23
-
-
Save Ilchert/37da01eaaf7a8ab883c80f197e62b20c to your computer and use it in GitHub Desktop.
HttpClinetConfig
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var builder = WebApplication.CreateBuilder(args); | |
builder.Services.AddHttpClient(); | |
builder.Services.AddSingleton<ICertificateProvider, CertificateProvider>(); | |
builder.Services.AddSingleton<IPostConfigureOptions<HttpClientFactoryOptions>, ConfigureHttpClientFactory>(); | |
var app = builder.Build(); | |
var factory = app.Services.GetRequiredService<IHttpClientFactory>(); | |
app.MapGet("/{clientId}", async (string clientId) => | |
{ | |
using var client = factory.CreateClient("cert_" + clientId); | |
_ = await client.GetAsync(""); | |
}); | |
await app.StartAsync(); | |
interface ICertificateProvider | |
{ | |
X509Certificate2 GetCertificate(string userId); | |
} | |
class CertificateProvider : ICertificateProvider | |
{ | |
public X509Certificate2 GetCertificate(string userId) | |
{ | |
return new X509Certificate2(); | |
} | |
} | |
class ConfigureHttpClientFactory(ICertificateProvider certificateProvider) : IPostConfigureOptions<HttpClientFactoryOptions> | |
{ | |
public void PostConfigure(string? name, HttpClientFactoryOptions options) | |
{ | |
if (name is null) | |
return; | |
if (!name.StartsWith("cert_")) | |
return; | |
var userId = name[5..]; | |
var certificate = certificateProvider.GetCertificate(userId); | |
options.HttpMessageHandlerBuilderActions.Add(b => | |
{ | |
if (b.PrimaryHandler is SocketsHttpHandler handler) | |
{ | |
handler.SslOptions ??= new(); | |
handler.SslOptions.ClientCertificates = [certificate]; | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment