BlueFox BlueFox - 11 months ago 75
C# Question

WCF per connection server certificate validation

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 connection.

From reading online, most (if not all) WCF related suggestion seems to point to the something similar of following

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

However, this is a global setting and I would like to apply this for only a specific connection. Is this even possible/supported usage scenario?

Answer Source

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();
        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.