Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bypass invalid SSL certificate in .net core

I am working on a project that needs to connect to an https site. Every time I connect, my code throws exception because the certificate of that site comes from untrusted site. Is there a way to bypass certificate check in .net core http?

I saw this code from previous version of .NET. I guess I just need something like this.

 ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; 
like image 520
Ramppy Dumppy Avatar asked Jul 01 '16 06:07

Ramppy Dumppy


People also ask

How do I enable SSL for a .NET project in Visual Studio?

Start Visual Studio 2019 and select Create a new project. In the Create a new project dialog, select ASP.NET Web Application (. NET Framework) > Next. In the Configure your new project dialog, enter SSLSample for Project name.


2 Answers

Update:

As mentioned below, not all implementations support this callback (i.e. platforms like iOS). In this case, as the docs say, you can set the validator explicitly:

handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; 

This works too for .NET Core 2.2, 3.0 and 3.1

Old answer, with more control but may throw PlatformNotSupportedException:

You can override SSL cert check on a HTTP call with the a anonymous callback function like this

using (var httpClientHandler = new HttpClientHandler()) {    httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };    using (var client = new HttpClient(httpClientHandler))    {        // Make your request...    } } 

Additionally, I suggest to use a factory pattern for HttpClient because it is a shared object that might no be disposed immediately and therefore connections will stay open.

like image 123
kdaveid Avatar answered Sep 19 '22 02:09

kdaveid


I solve with this:

Startup.cs

public void ConfigureServices(IServiceCollection services)     {         services.AddHttpClient("HttpClientWithSSLUntrusted").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler         {             ClientCertificateOptions = ClientCertificateOption.Manual,             ServerCertificateCustomValidationCallback =             (httpRequestMessage, cert, cetChain, policyErrors) =>             {                 return true;             }         }); 

YourService.cs

public UserService(IHttpClientFactory clientFactory, IOptions<AppSettings> appSettings)     {         _appSettings = appSettings.Value;         _clientFactory = clientFactory;     }  var request = new HttpRequestMessage(...  var client = _clientFactory.CreateClient("HttpClientWithSSLUntrusted");  HttpResponseMessage response = await client.SendAsync(request); 
like image 27
O.Machado Avatar answered Sep 19 '22 02:09

O.Machado