Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore "System.Net.Http.CurlException: Peer certificate cannot be authenticated with given CA certificates" on non-Windows platforms?

I have deployed a Kubernetes cluster in Microsoft Azure and would like to call some of the REST APIs from a .Net Core c# program using https. The certificates used when deploying the cluster not in a trusted CA. When I run this program on a Mac, I get the following error: "System.Net.Http.CurlException: Peer certificate cannot be authenticated with given CA certificates"

On Windows I'm able to set a custom ServerCertificateValidationCallback in order to ignore the error:

    WinHttpHandler winHttpHandler = new WinHttpHandler();
    winHttpHandler.ServerCertificateValidationCallback = ValidateServerCertificate;

public static bool ValidateServerCertificate(
    HttpRequestMessage request,
    X509Certificate certificate,
    X509Chain chain,
    SslPolicyErrors sslPolicyErrors)
{
    return true;
}

But, this is not supported under .Net Core on non-Windows platforms.

How can I ignore the error on other platforms?

like image 375
OlavT Avatar asked Apr 06 '17 13:04

OlavT


1 Answers

You can do this with .NET Core. We have been doing this with both 1.1, 2.0, and 2.1.

This can be done by constructing an HttpHandler and passing it into the HttpClient constructor. The HttpHandler has a ServerCertificateCustomValidationCallback, which you can override to perform custom certificate validation.

Sample:

private HttpClient SampleBuildHttpClient()
{
    return new HttpClient(
        new HttpClientHandler
        {
            ServerCertificateCustomValidationCallback = MyCallback,
        }); 
}

private bool MyCallback(HttpRequestMessage reqMsg, X509Certificate2 cert, X509Chain certChain, SslPolicyErrors policyErrors)
{
    //custom validation
    return true;
}
like image 189
Adrian Avatar answered Jan 03 '23 13:01

Adrian