Allowing Untrusted SSL Certificates with HttpClient
I'm struggling to get my Windows 8 application to communicate with my test web API over SSL.
It seems that HttpClient/HttpClientHandler does not provide and option to ignore untrusted certificates like WebRequest enables you to (albeit in a "hacky" way with ServerCertificateValidationCallback
).
Any help would be much appreciated!
Solution 1:
A quick and dirty solution is to use the ServicePointManager.ServerCertificateValidationCallback
delegate. This allows you to provide your own certificate validation. The validation is applied globally across the whole App Domain.
ServicePointManager.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;
I use this mainly for unit testing in situations where I want to run against an endpoint that I am hosting in process and am trying to hit it with a WCF client or the HttpClient
.
For production code you may want more fine grained control and would be better off using the WebRequestHandler
and its ServerCertificateValidationCallback
delegate property (See dtb's answer below). Or ctacke answer using the HttpClientHandler
. I am preferring either of these two now even with my integration tests over how I used to do it unless I cannot find any other hook.
Solution 2:
If you're attempting to do this in a .NET Standard library, here's a simple solution, with all of the risks of just returning true
in your handler. I leave safety up to you.
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
var client = new HttpClient(handler);
Solution 3:
Have a look at the WebRequestHandler Class and its ServerCertificateValidationCallback Property:
using (var handler = new WebRequestHandler())
{
handler.ServerCertificateValidationCallback = ...
using (var client = new HttpClient(handler))
{
...
}
}