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:
ServerCertificateValidationCallback

class CertificateHandler
{
public bool HandleCertificationCheck(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
//default
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!

iPhone/XCode - not all cases are equal!

This bit me! Having made some changes to an iPhone application (Obj-C); everything worked fine in the simulator. But, when deploying the s...