HttpWebRequest and Ignoring SSL Certificate Errors

Posted by Rick Strahl on West-Wind See other posts from West-Wind or by Rick Strahl
Published on Fri, 11 Feb 2011 13:14:45 GMT Indexed on 2011/02/25 7:25 UTC
Read the original article Hit count: 9918

Filed under:
|
|

Man I can't believe this. I'm still mucking around with OFX servers and it drives me absolutely crazy how some these servers are just so unbelievably misconfigured. I've recently hit three different 3 major brokerages which fail HTTP validation with bad or corrupt certificates at least according to the .NET WebRequest class. What's somewhat odd here though is that WinInet seems to find no issue with these servers - it's only .NET's Http client that's ultra finicky.

So the question then becomes how do you tell HttpWebRequest to ignore certificate errors? In WinInet there used to be a host of flags to do this, but it's not quite so easy with WebRequest.

Basically you need to configure the CertificatePolicy on the ServicePointManager by creating a custom policy. Not exactly trivial. Here's the code to hook it up:

public bool CreateWebRequestObject(string Url) 
{
    try 
    {
        this.WebRequest =  (HttpWebRequest) System.Net.WebRequest.Create(Url);
 
        if (this.IgnoreCertificateErrors)
            ServicePointManager.CertificatePolicy = delegate { return true; };
}

One thing to watch out for is that this an application global setting. There's one global ServicePointManager and once you set this value any subsequent requests will inherit this policy as well, which may or may not be what you want. So it's probably a good idea to set the policy when the app starts and leave it be - otherwise you may run into odd behavior in some situations especially in multi-thread situations.

Another way to deal with this is in you application .config file.

<configuration>

  <system.net>

    <settings>

      <servicePointManager

          checkCertificateName="false"

          checkCertificateRevocationList="false"         

      />

    </settings>

  </system.net>

</configuration>


This seems to work most of the time, although I've seen some situations where it doesn't, but where the code implementation works which is frustrating. The .config settings aren't as inclusive as the programmatic code that can ignore any and all cert errors - shrug.

Anyway, the code approach got me past the stopper issue. It still amazes me that theses OFX servers even require this. After all this is financial data we're talking about here. The last thing I want to do is disable extra checks on the certificates. Well I guess I shouldn't be surprised - these are the same companies that apparently don't believe in XML enough to generate valid XML (or even valid SGML for that matter)...

© Rick Strahl, West Wind Technologies, 2005-2011
Posted in .NET  CSharp  HTTP  
kick it on DotNetKicks.com

© West-Wind or respective owner

Related posts about .NET

Related posts about CSharp