Accepting Web Service Cerificates

12 February 2010

In the past, I have frequently tested in environments with self-generated SSL certificates, and then use "real" certificates in production environments. This usually is not much of a problem unless the application makes calls to web services that are also encrypted using a self-generated certificates. This scenario is increasingly the norm in the current world of SOA and RIA. For this scenario to work, you have to implement your own certificate validation code as follows:

 1 using System.Net;
 2 using System.Net.Security;
 3 using System.Security.Cryptography.X509Certificates;
 5 ServicePointManager.ServerCertificateValidationCallback = 
 6     delegate(Object senderCallback,
 7     X509Certificate certificate,
 8     X509Chain chain,
 9     SslPolicyErrors sslPolicyErrors)
10 {
11   //This implementation will ALWAYS accept 
12   //certificates whether or not they are expired 
13   //or from a hacker. Consider expanding this 
14   //code to verify that it came from your 
15   //Certificate Authority (CA), and that 
16   //it is not expired.
18   return true;
19 };

This delegate only has to be set once. Therefore, a good place to do this is at application start up. For an ASP.NET application, alter the Application_Start method of the Global.asax. For Sliverlight, see Application Startup.