Search code examples
c#windows-10certificatehttpclient

How should I use a certificate with HttpClient?


I need to use a web API from one of our partners. Their API require that I use a certificate to connect.

I do not want to install the certificate on our servers (VMs). That is counterproductive to our phoenix server strategy.

I try to use the certificate programmatically. The problem is that I get an error:

AuthenticationException: The remote certificate is invalid according to the validation procedure.

I create my HttpClient using this code:

_certificate = new X509Certificate2(_certificateFile);
var handler = new WebRequestHandler();
handler.ClientCertificates.Add(_certificate);
var client = new HttpClient(handler) { BaseAddress = new Uri(_url) };

I can make it work by overriding certificate validations:

ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };

But that looks like poor style.

I have verified that my endpoint matches CN in the certificate

Is the AuthenticationException simply because certificate is not installed in the certificate store?

If yes, can I temporarily with code install the certificate and remove it after?


Solution

  • "The remote certificate is invalid" indicates that .NET Framework thinks the server side certificate of your partner's web service is invalid (quite normal if you don't have necessary root/intermediate certificates installed).

    You can suppress the default check by changing ServerCertificateValidationCallback, but you should implement your own to make sure you do validate their certificate in a reasonable way to avoid attacks.

    You should also use HttpClientHandler.ServerCertificateValidationCallback, so that your custom validator only takes effect in the scope of this specific HttpClient instance, but does not affect elsewhere in your app,

    https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.servercertificatecustomvalidationcallback?view=netframework-4.8

    However, the certificate they gave you (usually a client certificate) is validated by their web service, not locally on your machine.