The SSL connection could not be established

C#Xamarin.Net Corexamarin.formsHttpclient

C# Problem Overview


I am using a third party library (Splunk c# SDK ) in my ASP.NET core application. I am trying to connect to my localhost Splunk service via this SDK, but I get an exception saying:

> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.

And The inner exception says:

> The remote certificate is invalid according to the validation procedure.

This SDK uses HTTP client under the hood, but I don't have access to this object to configure HttpClientHandler.

All my search on google ends up using ServicePointManager to bypass the SSL validation, but this solution doesn't work in Asp.Net core.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

Is there any way to bypass this validation in asp.Net core?

C# Solutions


Solution 1 - C#

Yes, you can Bypass the certificate using below code...

HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

// Pass the handler to httpclient(from you are calling api)
HttpClient client = new HttpClient(clientHandler);

Solution 2 - C#

As I worked with the identity server (.net core) and a web api (.net core) on my developer machine, I realized, that I need to trust the ssl certification of localhost. That command does the job for me:

dotnet dev-certs https --trust

Solution 3 - C#

This worked for me,

Create a Splunk.Client.Context by providing custom HttpClientHandler, that will bypass SSL invalid cert errors.

HttpClientHandler handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

// Create Context 
Context context = new Context(Scheme.Https, "localhost", 8089, default(TimeSpan), handler);

// Create Service
service = new Service(context);

Solution 4 - C#

If you are adding an IHttpClient and injecting through DI, u can add the configuration on the Startup.cs class.

public void ConfigureServices(IServiceCollection services)
        {
services.AddHttpClient("yourServerName").ConfigurePrimaryHttpMessageHandler(_ => new HttpClientHandler
            {
               ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }

            });
}

And then call it from your dependency injected class.

public class MyServiceClass 
    {
private readonly IHttpClientFactory _clientFactory;
public MyServiceClass (IConfiguration configuration, IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
} 

 public async Task<int> DoSomething()
{
var url = "yoururl.com";
var client = _clientFactory.CreateClient("yourServerName");
var result = await client.GetAsync(url);
}

Solution 5 - C#

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) =>
{
    // local dev, just approve all certs
    if (development) return true;
    return errors == SslPolicyErrors.None ;
};

This blog helped me

https://www.khalidabuhakmeh.com/validate-ssl-certificate-with-servicepointmanager

Solution 6 - C#

You get this error because your app isn't able to validate the certificate of the connection, and it's especially common to use this for the API that creates the session/login tokens. You can bypass it in a dangerous way as shown above, but obviously that's not a good solution unless you're just testing.

The best and easiest solution is to use the "modernhttpclient-updated" Nuget package, whose code is shared in this GitHub repo where there's also a lot of documentation.

As soon as you add the Nuget package, pass in a NativeMessageHandler into you HttpClient() as shown and build: var httpClient = new HttpClient(new NativeMessageHandler());

Now you will notice that you got rid of that error and will get a different error message like this Certificate pinning failure: chain error. ---> Javax.Net.Ssl.SSLPeerUnverifiedException: Hostname abcdef.ghij.kl.mn not verified: certificate: sha256/9+L...C4Dw=

To get rid of this new error message, you have to do add the hostname and certificate key from the error to a Pin and add that to the TLSConfig of your NativeMessageHandler as shown:

var pin = new Pin();
pin.Hostname = "abcdef.ghij.kl.mn";
pin.PublicKeys = new string[] { "sha256/9+L...C4Dw=" };
var config = new TLSConfig();
config.Pins = new List<Pin>();
config.Pins.Add(pin);
httpClient = new HttpClient(new NativeMessageHandler(true, config)

Keep in mind that your other (non token generating) API calls may not implement certificate pinning so they may not need this, and frequently they may use a different Hostname. In that case you will need to register them as pins too, or just use a different HttpClient for them!

Solution 7 - C#

Installing the .NET Core SDK installs the ASP.NET Core HTTPS development certificate to the local user certificate store. The certificate has been installed, but it's not trusted. To trust the certificate, perform the one-time step to run the dotnet dev-certs tool:

dotnet dev-certs https --trust

for more information visit this link

Solution 8 - C#

I had to turn off my vpn to get rid off this error

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMVafaView Question on Stackoverflow
Solution 1 - C#Rohit JangidView Answer on Stackoverflow
Solution 2 - C#Daniel MichelfelderView Answer on Stackoverflow
Solution 3 - C#Piyush SagarView Answer on Stackoverflow
Solution 4 - C#Yamil OrtegaView Answer on Stackoverflow
Solution 5 - C#Diego Mauricio GuerreroView Answer on Stackoverflow
Solution 6 - C#SaamerView Answer on Stackoverflow
Solution 7 - C#MertHaddadView Answer on Stackoverflow
Solution 8 - C#Muhammad AwaisView Answer on Stackoverflow