Search code examples
c#asp.net-coredependency-injectiondotnet-httpclient

Disable SSL certificate verification in default injected IHttpClientFactory


In Startup.cs I inject an IHttpClientFactory service:

services.AddHttpClient();

I can then create a new HttpClient through

public MyClass(IHttpClientFactory httpClientFactory, IOptions<MyClassOptions> options)
{
    _httpClient = httpClientFactory.CreateClient();
    // ...
}

MyClass does some API access; the base URL is passed in the options object.

For testing I set up a dummy instance of the API, which uses a self-signed SSL certificate. Unfortunately, this certificate is (correctly) recognized as invalid:

System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
 ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

How can I disable certificate verification at the factory layer, i.e. directly in the ConfigureServices method?

I found this question, but it seemed to use some custom HttpClient implementation (?), while I want to target the default one. The following does not work (DI picks the wrong constructor and subsequently fails):

services.AddHttpClient<IMyClass, MyClass>();

This answer suggests to supply a name for the configured HttpClient, but it passes some magic string, which I would like to avoid (MyClass is located in a class library designed to be also used by others). Passing no name does not work either, since AddHttpClient then merely returns an IServiceCollection object.


Solution

  • I figured it out now. We can apply this answer to modify the primary HttpMessageHandler of the default HttpClient:

    services.AddHttpClient(Options.DefaultName, c =>
    {
        // ...
    }).ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler
        {
            ClientCertificateOptions = ClientCertificateOption.Manual,
            ServerCertificateCustomValidationCallback =
                (httpRequestMessage, cert, certChain, policyErrors) => true
        };
    });
    

    This will yield HttpClient objects with disabled SSL verification, whenever the default IHttpClientFactory is injected.