January 29, 2021

Call WCF - Set SecurityProtocol & ServerCertificateValidationCallback

.Net Applications use ServicePointManager.SecurityProtocol Property to specify the version of the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocol for new connections, existing connections aren't changed.

It is recommended that you should not specify this property manually and let it be use its default value, which will be obtained from machine configuration. Still In some scenarios, you may want to specifically define the SecurityProtocol when calling a WCF service with Https link. In this case you can define the required protocols like this:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                   | SecurityProtocolType.Tls11
                   | SecurityProtocolType.Tls12
                   | SecurityProtocolType.Ssl3;

Since these are flags, so you can use bitwise OR(|) operator to specifiy multiple protocols if your connection requires.

Another property is ServerCertificateValidationCallback, which is used by the client to perform custom validation for the server certificate. The 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.

If you trust the server and not using custom validation, you can simply return true from the callback method.

 
ServicePointManager.ServerCertificateValidationCallback =
             new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);

Here is the definition of IgnoreCertificateErrorHandler, which will always return true.

private static bool IgnoreCertificateErrorHandler(object sender,
   X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{​​​​​​​
	return true;
}​​​​​​​

You can also replace the above callback method definition with a short-hand delegate syntax.

ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };

References:

No comments:

Post a Comment