WCF per connection server certificate validation

前端 未结 7 2796
清歌不尽
清歌不尽 2021-02-20 13:50

I\'m trying to bypass https certificate validation only to our own testing environment (multiple machines), while trying to keep certificate validation for all the other connect

7条回答
  •  有刺的猬
    2021-02-20 14:01

    Something like this:

    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(ValidateCert);
    
    public static bool ValidateCert(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        string requestHost;
    
        if(sender is string)
        {
            requestHost = sender.ToString();
        }
        else
        {
            HttpWebRequest request = sender as HttpWebRequest;
    
            if(request != null)
            {
                requestHost = request.Host;
            }
        }
    
        if(!string.IsNullOrEmpty(requestHost) && requestHost == "my_test_machine")
            return true;
    
        return sslPolicyErrors == SslPolicyErrors.None;
    }
    

    Note the documentation on the sender parameter:

    sender parameter passed to the RemoteCertificateValidationCallback can be a host string name or an object derived from WebRequest (HttpWebRequest, for example) depending on the CertificatePolicy property

    Disclaimer - I didn't test this, I wrote it based on the documentation. YMMV.

提交回复
热议问题