Unable to use dynamic client certificate with HttpClientFactory
Hello, I used HttpClient before:
var certificate = ...
var password = ...
using (var clientHandler = new HttpClientHandler())
{
clientHandler.ClientCertificates.Add(new X509Certificate2(certificate , password ));
using (var certificateClient = new HttpClient(clientHandler))
{
// ...
}
}
The certificate is dynamic and is obtained from the database.
unable to services.AddHttpClient for all certificates in ConfigureServices.
Can you tell me how it should be implemented?
You can use ConfigurePrimaryHttpMessageHandler to set up the message handler with a certificate:
services.AddHttpClient("example").ConfigurePrimaryHttpMessageHandler(() =>
{
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);
return handler;
});
The callback is generally called when the HttpClient is being constructed, so it does not happen at the startup time but on-demand when the client is being used. This means that you can effectively configure the certificate at run-time.
It’s also possible to depend on the service provider there, so you could have some other dependency that provides you with the right certificate:
services.AddHttpClient("example").ConfigurePrimaryHttpMessageHandler(sp =>
{
var certificateProvider = sp.GetService<CertificateProvider>();
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificateProvider.GetCertificate());
return handler;
});
@poke How to ensure that it is correct when multiple certificates are used?
Not every IHttpClientFactory.CreateClient("example") can trigger services.AddHttpClient("example").ConfigurePrimaryHttpMessageHandler,
so this only works for a single certificate.
You should configure a client for each certificate you need. Each client should only have a single configuration.
What should I do when the certificate changes?
use dynamic client certificate with HttpClientFactory Is there a solution?
What does “dynamic” mean to you? You could always reconfigure the client (or rather parameterize the configuration).
We do sass. Certificates are stored in databases and different customers use different certificates. So every time we use client, we need to configure certificates. Now they can only be used in starup.cs.
ConfigurePrimaryHttpMessageHandler(() =>
{
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);
return handler;
});
We also use it like @anhuisunfei describe it, we can also change it in runtime depending of some factors, to know and create them only in Setup is quite limiting.
use dynamic client certificate with HttpClientFactory Is there a solution?
Did anyone figure this out? With the SocketsHttpHandler it's possible to write logic to that runs per connection to determine which client certificate to use.