C# Ignore certificate errors?

后端 未结 11 1042
鱼传尺愫
鱼传尺愫 2020-11-22 15:01

I am getting the following error during a web service request to a remote web service:

Could not establish trust relationship for the SSL/TLS secure c

相关标签:
11条回答
  • 2020-11-22 15:25

    Allowing all certificates is very powerful but it could also be dangerous. If you would like to only allow valid certificates plus some certain certificates it could be done like this.

    .Net core:

    using (var httpClientHandler = new HttpClientHandler())
    {
        httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return true;   //Is valid
            }
    
            if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
            {
                return true;
            }
            return false;
        };
        using (var httpClient = new HttpClient(httpClientHandler))
        {
            var httpResponse = httpClient.GetAsync("https://example.com").Result;
        }
    }
    

    .Net framework:

    System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate (
        object sender,
        X509Certificate cert,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            return true;   //Is valid
        }
    
        if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
        {
            return true;
        }
    
        return false;
    };
    

    Update:

    How to get cert.GetCertHashString() value in Chrome:

    Click on Secure or Not Secure in the address bar.

    Then click on Certificate -> Details -> Thumbprint and copy the value. Remember to do cert.GetCertHashString().ToLower().

    0 讨论(0)
  • 2020-11-22 15:30

    If you are using sockets directly and are authenticating as the client, then the Service Point Manager callback method won't work. Here's what did work for me. PLEASE USE FOR TESTING PURPOSES ONLY.

    var activeStream = new SslStream(networkStream, false, (a, b, c, d) => { return true; });
    await activeStream.AuthenticateAsClientAsync("computer.local");
    

    The key here, is to provide the remote certificate validation callback right in the constructor of the SSL stream.

    0 讨论(0)
  • 2020-11-22 15:33

    The reason it's failing is not because it isn't signed but because the root certificate isn't trusted by your client. Rather than switch off SSL validation, an alternative approach would be to add the root CA cert to the list of CAs your app trusts.

    This is the root CA cert that your app currently doesn't trust:

    -----BEGIN CERTIFICATE-----
    MIIFnDCCBISgAwIBAgIBZDANBgkqhkiG9w0BAQsFADBbMQswCQYDVQQGEwJDWjEs
    MCoGA1UECgwjxIxlc2vDoSBwb8WhdGEsIHMucC4gW0nEjCA0NzExNDk4M10xHjAc
    BgNVBAMTFVBvc3RTaWdudW0gUm9vdCBRQ0EgMjAeFw0xMDAxMTkwODA0MzFaFw0y
    NTAxMTkwODA0MzFaMFsxCzAJBgNVBAYTAkNaMSwwKgYDVQQKDCPEjGVza8OhIHBv
    xaF0YSwgcy5wLiBbScSMIDQ3MTE0OTgzXTEeMBwGA1UEAxMVUG9zdFNpZ251bSBS
    b290IFFDQSAyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoFz8yBxf
    2gf1uN0GGXknvGHwurpp4Lw3ZPWZB6nEBDGjSGIXK0Or6Xa3ZT+tVDTeUUjT133G
    7Vs51D6z/ShWy+9T7a1f6XInakewyFj8PT0EdZ4tAybNYdEUO/dShg2WvUyfZfXH
    0jmmZm6qUDy0VfKQfiyWchQRi/Ax6zXaU2+X3hXBfvRMr5l6zgxYVATEyxCfOLM9
    a5U6lhpyCDf2Gg6dPc5Cy6QwYGGpYER1fzLGsN9stdutkwlP13DHU1Sp6W5ywtfL
    owYaV1bqOOdARbAoJ7q8LO6EBjyIVr03mFusPaMCOzcEn3zL5XafknM36Vqtdmqz
    iWR+3URAUgqE0wIDAQABo4ICaTCCAmUwgaUGA1UdHwSBnTCBmjAxoC+gLYYraHR0
    cDovL3d3dy5wb3N0c2lnbnVtLmN6L2NybC9wc3Jvb3RxY2EyLmNybDAyoDCgLoYs
    aHR0cDovL3d3dzIucG9zdHNpZ251bS5jei9jcmwvcHNyb290cWNhMi5jcmwwMaAv
    oC2GK2h0dHA6Ly9wb3N0c2lnbnVtLnR0Yy5jei9jcmwvcHNyb290cWNhMi5jcmww
    gfEGA1UdIASB6TCB5jCB4wYEVR0gADCB2jCB1wYIKwYBBQUHAgIwgcoagcdUZW50
    byBrdmFsaWZpa292YW55IHN5c3RlbW92eSBjZXJ0aWZpa2F0IGJ5bCB2eWRhbiBw
    b2RsZSB6YWtvbmEgMjI3LzIwMDBTYi4gYSBuYXZhem55Y2ggcHJlZHBpc3UvVGhp
    cyBxdWFsaWZpZWQgc3lzdGVtIGNlcnRpZmljYXRlIHdhcyBpc3N1ZWQgYWNjb3Jk
    aW5nIHRvIExhdyBObyAyMjcvMjAwMENvbGwuIGFuZCByZWxhdGVkIHJlZ3VsYXRp
    b25zMBIGA1UdEwEB/wQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQW
    BBQVKYzFRWmruLPD6v5LuDHY3PDndjCBgwYDVR0jBHwweoAUFSmMxUVpq7izw+r+
    S7gx2Nzw53ahX6RdMFsxCzAJBgNVBAYTAkNaMSwwKgYDVQQKDCPEjGVza8OhIHBv
    xaF0YSwgcy5wLiBbScSMIDQ3MTE0OTgzXTEeMBwGA1UEAxMVUG9zdFNpZ251bSBS
    b290IFFDQSAyggFkMA0GCSqGSIb3DQEBCwUAA4IBAQBeKtoLQKFqWJEgLNxPbQNN
    5OTjbpOTEEkq2jFI0tUhtRx//6zwuqJCzfO/KqggUrHBca+GV/qXcNzNAlytyM71
    fMv/VwgL9gBHTN/IFIw100JbciI23yFQTdF/UoEfK/m+IFfirxSRi8LRERdXHTEb
    vwxMXIzZVXloWvX64UwWtf4Tvw5bAoPj0O1Z2ly4aMTAT2a+y+z184UhuZ/oGyMw
    eIakmFM7M7RrNki507jiSLTzuaFMCpyWOX7ULIhzY6xKdm5iQLjTvExn2JTvVChF
    Y+jUu/G0zAdLyeU4vaXdQm1A8AEiJPTd0Z9LAxL6Sq2iraLNN36+NyEK/ts3mPLL
    
    -----END CERTIFICATE-----
    

    You can decode and view this certificate using

    this certificate decoder or another certificate decoder

    0 讨论(0)
  • 2020-11-22 15:34

    This code worked for me. I had to add TLS2 because that's what the URL I am interested in was using.

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    ServicePointManager.ServerCertificateValidationCallback +=
        (sender, cert, chain, sslPolicyErrors) => { return true; };
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(UserDataUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new
          MediaTypeWithQualityHeaderValue("application/json"));
        Task<string> response = client.GetStringAsync(UserDataUrl);
        response.Wait();
    
        if (response.Exception != null)
        {
             return null;
        }
    
        return JsonConvert.DeserializeObject<UserData>(response.Result);
    }
    
    0 讨论(0)
  • 2020-11-22 15:34

    Bypass SSL Certificate....

            HttpClientHandler clientHandler = new HttpClientHandler();
            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
    
            // Pass the handler to httpclient(from you are calling api)
            var client = new HttpClient(clientHandler)
    
    0 讨论(0)
  • 2020-11-22 15:37

    To disable ssl cert validation in client configuration.

    <behaviors>
       <endpointBehaviors>
          <behavior name="DisableSSLCertificateValidation">
             <clientCredentials>
                 <serviceCertificate>
                    <sslCertificateAuthentication certificateValidationMode="None" />
                  </serviceCertificate>
               </clientCredentials>
            </behavior>
    
    0 讨论(0)
提交回复
热议问题