Bypass invalid SSL certificate in .NET CORE under testing environment

SSL connection problem
  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.
// 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;
});
}

Reference

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store