Bypass SSL certificate validation
A workaround quick solution when your SSL certificate expires
It is a common thing that some of your application functionalities depend on an external HTTPS endpoint. However, renewal of SSL certificate for the external party is out of your control and you have to rely on the third party that certificate will be renewed on time. If renewal does not happen on time, SSL certificate becomes invalid.
.NET has by default build in mechanism to throw an exception if you are trying to make a WebRequest to HTTPS endpoint which has invalid SSL certificate. In other words, .NET is doin SSL certificate validation for you under the hood.
The following code snippet is one of the cases you might get into this exception thrown by your code.
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://someurl.com/service/"); HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
inner Exception.Message is:
"The remote certificate is invalid according to the validation procedure."
This exception is caused by invalid or expired SSL certificate. As soon as SSL certificate is expired, server will start to use self-signed certificate which fails validation.
Even if you try to access the URL to which you are trying to create a request in a browser you will get the following screen
How ever you can resolve this issue by declaring custom validation method.
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
In this example, validation method is overridden by custom method which always returns true value.
So before making a request, declare this callback method
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://someurl.com/service/"); HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
This way, validation will always pass as your custom method always returns true value.
References
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article