louisjrdev

Ignore SSL validity with HttpClient


Warning

Now please bear in mind that this is extremely unsafe as any requests made (even others in other areas of your app) may now use this callback and deem the responding certificate valid when there could be a malicuous actor with a dodgy certificate on the other end.

Use at your own risk and never commit this to your repo or production environment.

In this particular example, I only used this locally for performing a quick test in an isolated environment where I knew no requests could be made to any potentially comprimised third party sites.

Problem

So with that out of the way, I came across a bit of annoying issue the other day, when having a .net web app make a request to one of our API’s It threw an exception. This was a bit odd, because there was no such bug in the particular execution path but it was still failing.

So I had a proper look at the exception and it turned out, that my local development SSL certificate wasn’t being deemed valid / trusted by HttpClient. Now I am almost certain this is caused by me messing around with my local development SSL certificates at some point.

However, solving this SSL certificate issue would be no small feat, at least not for me (with my fuzzy knowledge of local SSL certificates) and with not really enough time to fix it. As I have spent a few hours in the past trying to resolve this issue.

Solution

So the nice one liner to save the day is, pop this somewhere in your code before you make your request:

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => cert.Issuer == “localhost”;

So this callback gets run everytime a certificate is validated, we are overriding the behaviour to say if the issuer of the certificate is localhost then, return true to signfy it as being valid. Alternatively you can just have this return true to have all certificates be deemed valid, but that is even riskier.