Troubleshooting : EWS request throws “The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel” ?
One of my customer updated that whenever they try to make the remote Exchange Web Service (EWS) call from his C#.Net 2008 application (VS.Net 2008 - .Net Framework 3.x), he gets the following error:
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel
I had a detailed look at their application code.
// Create the Exchange Service Binding
ExchangeServiceBinding esb = new ExchangeServiceBinding();
// Add its relevant Credentials like user name, password, domain and URL
esb.Credentials = new NetworkCredential(userName, Password, domain);
esb.Url = @"https://myexchangeserver/EWS/Exchange.asmx";
We checked the credentials passed; it seems everything was fine. But still it was failing whenever we make the request to the server with the above same message. When we checked their environment, we found customer uses the self-signed certificate on the server. This is because, by default, .NET checks whether SSL certificates are signed by a certificate from the Trusted Root Certificate store.
To over-ride this behavior, we need to use the following line in the code, which validate the x509 certificate:
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
This will accept all certificates, regardless of why they are invalid, which resolved the customer’s issue.
By validating the X509 certificate provided by the computer running Microsoft Exchange Server 2007 for SSL over HTTP, you help to provide a layer of security for the client application. You must validate certificates before you can start programming with Exchange Web Services proxy classes. If the callback is not set up, the first call will fail with a certificate error.