Tuesday, May 08, 2007

Ignoring SSL Certificate Problems

Have you ever run across these problems when trying to connect to a secure web service?

"The remote certificate is invalid according to the validation procedure",
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."

Usually this is caused by a bad certificate on the server side, but what if you want to connect anyway, maybe you trust the remote system and just don't care. How do you get around this? How do you get your code to ignore these warnings and continue? We'll if you're using .NET 2.0 it's really easy (still pretty easy in .NET 1 but it takes a little more work). You'll need to use the ServicePointManager class, and add this using statement (if you don't want to use the fully qualified names anyway).

using System.Security.Cryptography.X509Certificates;
Now all you need to do is add this bit of code somewhere before you make the call to the web service.
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors) {
return true;
The 'ServerCertificateValidationCallback' is used to custom validate server certificates. By default it is null, and since the above code just returns 'true' all certificates will be valid now. You could add some more custom code to this if you wanted to do your own validation, say you only want it to be valid if the cert comes from a specific place etc.
You can also check out this MS link as well that has the same code as above

1 comment:

Anonymous said...

Great and simple solution! Thanks