Bypass invalid SSL certificate in .NET CORE under testing environment

LAI TOCA
3 min readApr 29, 2022

--

Microservice was conventional practice nowadays. The application(s) connected to internal or external APIs for exchange data of common ways. But we might suddenly occurred below error since we try to fire http connection through the help of .NET HttpClient:

SSL connection problem

The main reason here was that application need establish connection with third-party APIs but SSL certificate validate got failed. Here was solution that we apply for both development and production environments:

  1. Configure the HttpMessageHandler under ConfigureServices, then we could create HttpClient using IHttpClientFactory.CreateClient(“Name”).
  2. For the development phrase, always return true to bypass validation of certification under delegate of ServerCertificateCustomValidationCallback.
  3. For the production we could build up the white list of thumbprint under appsettings.json (property: CertThumbprint).
  4. If the configuration field CertThumbprint has not been setup then check if errors equal to SslPolicyErrors.None.
  5. If configuration field CertThumbprint has specific value then only accept the settings certification.

The completed code snippet as below:

// Startup.cs
// We could register and setup handler for http request
// under ConfigureServices
public void ConfigureServices (IServiceCollection services) {
//........
services.AddHttpClient ("Name")
.ConfigurePrimaryHttpMessageHandler (() => {
var handler = new HttpClientHandler {
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
ServerCertificateCustomValidationCallback = (sender, certificate, chain, errors) => {
#if DEBUG
return true; // DEV
#else
if (string.IsNullOrEmpty (config.AppBaseInfo.CertThumbprint)) {
return errors == SslPolicyErrors.None;
} else {
return errors == SslPolicyErrors.None &&
certificate.Thumbprint.Equals (config.AppBaseInfo.CertThumbprint, StringComparison.OrdinalIgnoreCase);
}
#endif
}
};
return handler;
});
}

We could also used GetCertHashString() to get the thumbprint as well: certificate.Thumbprint == certificate.GetCertHashString().

The next question would be, where to found the thumbprint? We could open browser and visit the “Get” Http method:

Then go to Details tab then we could having thumbprint here:

We used Chrome as example, if you are familiar postman then you could retrieved certificate information inside the console windows:

Reference

--

--

LAI TOCA

Coding for fun. (Either you are running for food or running for being food.)