26 March, 2007

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS

Update: Since this post – anonymous methods and lambda statements have arrived. This is a lot simpler statement:

ServicePointManager.ServerCertificateValidationCallback = (obj, s, cert, chain) => { return true; };


I today encountered the dreaded exception: "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel" when trying to communicate with an SSL webservice.

The reason was as expected that the certificate presented by the webserver (integral part of an IHC controller) was not trusted by my Client PC. To retrieve this certificate was far from easy, hence I solved the issue by using a workaround that allows you to hook into the certificate validation mechanism on the client side.

Create a class that exposes a method matching the delegate:

class CertificateHandler
public bool HandleCertificationCheck(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
return true;

Hook together your code using the ServicePointManager like this:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(new CertificateHandler().HandleCertificationCheck);

Now the certificate validation is performed from your own code! Returning true to everything of-course means that you trust everything which is somewhat of a statement; but in some scenarios it can be necessary if you are in a controlled environment.

Technorati Tags:

1 comment:

Anonymous said...

Worked like a charm ... thanks!

InRiver: Not loading your extensions?

(You really need to in the loop to appreciate the issue this post addresses). Man, I've been fighting this problem for hours before I ...