Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow all https regardless of validity in .NET Core HttpClient?

I am creating a web API in .NET Core. To debug it locally, I have created a console application that connects to my API. I am debugging in Linux.

When connecting to my local URL at https://localhost:5001/, my console application is throwing an AuthenticationException (The remote certificate is invalid according to the validation procedure).

I have tried to circumvent this in two ways:

  1. Have added ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; but it has no effect.

  2. I have run dotnet dev-certs https --trust. Now my web browser doesn't complain anymore, which is nice, but my console application is still throwing the exception. Have tried rebooting.

How can I make .NET Core trust my localhost server? Or ignore the certificate validity?

like image 726
HelloWorld Avatar asked Apr 15 '19 09:04

HelloWorld


People also ask

What is the use of UseHttpsRedirection?

app. UseHttpsRedirection(); is a single line code, which you have to write under Configure method to secure . NET Core solutions. Moreover, you don't always have to configure this middleware, as most ASP.NET web app templates, such as MVC, come with it by default enabled with it.

What is ServerCertificateCustomValidationCallback?

The ServerCertificateCustomValidationCallback can be used to obtain and validate the server certificate.


2 Answers

Use the sample below from here

var httpClientHandler = new HttpClientHandler();
// Return `true` to allow certificates that are untrusted/invalid
httpClientHandler.ServerCertificateCustomValidationCallback = 
    HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
var httpClient = new HttpClient(httpClientHandler);
like image 166
Bassam Gamal Avatar answered Oct 26 '22 23:10

Bassam Gamal


I found the solution:

var httpClientHandler = new HttpClientHandler();

httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true; // DEBUGGING ONLY

var httpClient = new HttpClient(httpClientHandler);

Although it is still unclear to me why the certificate is not considered valid after running dotnet dev-certs https --trust.

like image 37
HelloWorld Avatar answered Oct 26 '22 21:10

HelloWorld