Bypass invalid SSL certificate in .NET CORE under testing environment
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:
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:
- Configure the HttpMessageHandler under ConfigureServices, then we could create HttpClient using IHttpClientFactory.CreateClient(“Name”).
- For the development phrase, always return true to bypass validation of certification under delegate of ServerCertificateCustomValidationCallback.
- For the production we could build up the white list of thumbprint under appsettings.json (property: CertThumbprint).
- If the configuration field CertThumbprint has not been setup then check if errors equal to SslPolicyErrors.None.
- 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: