Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

HttpWebRequest and Ignoring SSL Certificate Errors


:P
On this page:

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)...

Posted in .NET  CSharp  HTTP  

The Voices of Reason


 

matt
April 12, 2007

# re: HttpWebRequest and Ignoring SSL Certificate Errors

You can go another route

System.Net.ServicePointManager.ServerCertificateValidationCallback +=
    delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                            System.Security.Cryptography.X509Certificates.X509Chain chain,
                            System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true; // **** Always accept
        };




http://mhinze.com/consuming-web-services-crafting-webrequests-using-ssl-where-the-cert-is-expired-or-otherwise-hosed/

Rick Strahl
April 12, 2007

# re: HttpWebRequest and Ignoring SSL Certificate Errors

Thanks Matt - I changed that last night actually seeing that the code I posted is flagged as deprecated <s>. Still has the same issue though in that it's globally tied to the ServicePointManager and so will affect all HTTP sessions.

Aaron
April 12, 2007

# re: HttpWebRequest and Ignoring SSL Certificate Errors

I think you could check the Sender parameter, If its your webservice class invoke always true. If its not invoke the other policy delegate.

Bob Wohler
April 24, 2007

# re: HttpWebRequest and Ignoring SSL Certificate Errors

Is there a way to configure this using web.config?

Rick Strahl's Web Log
June 23, 2007

# Rick Strahl's Web Log


Richard Norris
November 16, 2007

# re: HttpWebRequest and Ignoring SSL Certificate Errors

This is great, although I agree rather awkward compared to native WinInet API's. The classes to implement do not seem to exist in .NETCF2.0. Does anyone know the eqivilent code in .NETCF?

Many Thanks

Seth
January 26, 2008

# re: HttpWebRequest and Ignoring SSL Certificate Errors

This is great for always ignoring the cert errors but what if I want to trap or log specific errors? What if I want to ignore an expired cert but do NOT want to ignore a cert where the cert is malformed (fer instance)?

Rick Strahl
January 27, 2008

# re: HttpWebRequest and Ignoring SSL Certificate Errors

That's what the actual method is for. You can look at the messages and log if you find a cert error.

maila
July 04, 2008

# re: HttpWebRequest and Ignoring SSL Certificate Errors

thanks i resolved my problem using this code.

John Leger
November 14, 2008

# re: HttpWebRequest and Ignoring SSL Certificate Errors

Rick,

I have run into situations where the SSL is not the problem but rather the authority name is limited to one domain. In the situation where the certificate simply needs to be altered to include alternate domain names (SubjectAlternativeDomain) would you not agree this is advisable over simply ignoring all SSL Certificate errors? I was under the impression you could not trap the error when a user navigates to a secure page of an unauthorized certificate domain name but a valid App Domain. I was trying to solve in code via the Application_BeginRequest method.

Jason Fay
January 13, 2009

# re: HttpWebRequest and Ignoring SSL Certificate Errors

Thanks for posting this. Deprecated but works!

Mike Bridge
February 23, 2009

# re: HttpWebRequest and Ignoring SSL Certificate Errors

Here's a more concise variant with 3.5:

ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain,
sslPolicyErrors) => true);

Joel Holder
March 05, 2010

# re: HttpWebRequest and Ignoring SSL Certificate Errors

Thanks for pulling this together Rick. Exactly what I needed to overcome lame cert on end that I don't control. Peace out..

Chili
April 28, 2010

# re: HttpWebRequest and Ignoring SSL Certificate Errors

I'm trying upload file to a server https but upload failed. This server is an Apache. I have the
trace and the socket is up but don't receive. I receive a Statuscode 200(OK). What's wrong?
Thanks in advance

Alex
September 16, 2010

# re: HttpWebRequest and Ignoring SSL Certificate Errors

here's an even more concise form:
ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };

Johan Botha
November 15, 2012

# re: HttpWebRequest and Ignoring SSL Certificate Errors

Rick,
I know this is old, but I wrote my own endpoint manager, that way I can call it and tell it to ignore cert errors for a specific url. The callback delegate will then run through that cached dictionary to see if it needs to ignore a cert error or not for the specific url. That seemed safer for me. Since all my Http calls go through a helper for that (part of its code probably came from your stuff), I have an endpoint definition that is passed in, which includes a flag on whether to ignore cert errors for that endpoint. It has worked very well, important to keep in mind multiple threads in the manager though, since we do 200 transactions per second.

Naveed Iqbal
February 13, 2013

# re: HttpWebRequest and Ignoring SSL Certificate Errors

Where do I exactly place the code ? Currently I have placed in the Application_Start() event in the global.asax.cs

Rick Strahl
February 13, 2013

# re: HttpWebRequest and Ignoring SSL Certificate Errors

@Naveed - where you place it is up to you, but yes - usually application startup is the place to do it since it is effectively a global setting.

MS
February 06, 2014

# re: HttpWebRequest and Ignoring SSL Certificate Errors

i get this error sometimes when i read outlook mail programmatically using IMAP.

"The remote certificate is invalid according to validation procedure:" Pls help :(

Michael Bray
October 21, 2014

# re: HttpWebRequest and Ignoring SSL Certificate Errors

FYI this can now be set per-connection on HttpWebRequest in .NET 4.5

Bassem Mohsen
July 01, 2015

# re: HttpWebRequest and Ignoring SSL Certificate Errors

To elaborate on Michael Bray's comment, here is how you skip the certificate validation for a particular request without affecting the rest of the application.

httpWebRequest.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

This code requires .NET 4.5 or a later version.

jefferson vaughn
July 31, 2020

# re: HttpWebRequest and Ignoring SSL Certificate Errors

I realize the post is old... but not finding any real good solutions yet...

my domain jeffersonvaughn.com is hosting a website in which I am running a .net core 3.1 application that executes a POST method HTTP request to server jvaughn1.powerbunker.com

I have generated a certificate on the jvaughn1.powerbunker.com server and have exported to a .pfx file in which I'm using in my .net application.

this http api request along with this .pfx file works when using Postman.

When my .net application makes the request I get...

An unhandled exception occurred while processing the request.
AuthenticationException: The remote certificate is invalid according to the validation procedure.
System.Net.Security.SslStream.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception)

HttpRequestException: The SSL connection could not be established, see inner exception.
System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)

my .net code looks like this...

startup...

            var cert = new X509Certificate2(@"C:\Users\jeffe\Desktop\Corei Solutions\products\core-i_rst\Apache HTTP_SSL\jvaughn1.powerbunker.com.pfx"
                                           , "corei");

            var handler = new HttpClientHandler()
            {
                SslProtocols = SslProtocols.Tls13 | SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls
            };

            handler.ClientCertificates.Add(cert);
            services.AddHttpClient("coreiClient", c =>
            {
            }).ConfigurePrimaryHttpMessageHandler(() => handler);

            // handles issue with non-trusted certs...
            ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };

controller...

        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            //RequestUri = new Uri(Url + jsonRequest),
            RequestUri = new Uri(g_Url),
            Content = new StringContent(jsonRequest, System.Text.Encoding.Default, "text/plain"),
        };

        // for certificate authentication...
        var client = _clientFactory.CreateClient("coreiClient");

        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

Is there ANY possible way you can help shed some light on this and save me from this nightmare I been trying to wake up from!!!??? 😃


West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024