Dealing with expired certificates and .NET’s HTTPWebRequest object

By reeset / On / In Microsoft, Programming

Some folks that had tried using the Verify URL utility had notified me that it wasn’t reporting a response status when attempting to query materials through an ezproxy url.  The problem it appears, was that the servers in question had either expired security certificates or certificates that were not issued by a trusted site (i.e., hasn’t gone through Microsoft’s verification process).  Well, in .NET, the HTTPWebResponse object cannot accept data by default from a site with an invalid or expired security certificate.  Since this is likely going to be an ongoing problem, I ended up needing to setup a class that would reset the application’s CertificatePolicy object.  To do this, you basically need to setup a class that will accept all Certificates given to it.  Obviously doing this requires a bit of trust — and in this case, since the URLs are coming from MARC records and only being used to read headers–I think we can make that leap.  Anyway, to reset the .NET CertificatePolicy object, you need to setup a class that looks something like this:

internal class AcceptAllCertificatePolicy : System.Net.ICertificatePolicy {public AcceptAllCertificatePolicy() {}

public bool CheckValidationResult(System.Net.ServicePoint sPoint, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Net.WebRequest wRequest,int certProb){// Always accept

return true; }}

To make use of this function, you need to call this class before you initialize the HTTPWebRequest object with a call like:

System.Net.ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();