109

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?

6
  • 3
    Can't you register the certificate of the localhost service with your machine, so that it becomes valid? Oct 23, 2018 at 0:37
  • 1
    @John How can I register that? Can you please elaborate?
    – MVafa
    Oct 23, 2018 at 5:25
  • 1
    Is your localhost server ASP.NET too? Or? Oct 23, 2018 at 5:27
  • 1
    @John No it is not. The server is Splunk Enterprise, I just download and install it, it hosts the service on localhost:8089
    – MVafa
    Oct 23, 2018 at 5:30
  • 1
    You'll need to find some way to export the SSL certificate it's using, or use your own self-signed certificate. Then you can add it to Windows through certmgr.msc Oct 23, 2018 at 5:53

13 Answers 13

198

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);
4
  • 39
    note that this solution just removes all certificate validation from your code and is thus a security issue! Sep 3, 2020 at 7:43
  • 1
    Where in an MVC project should this be placed?
    – Bbb
    Apr 11, 2022 at 12:02
  • 1
    A less security breaching solution that works in our case : clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => cert.Verify()
    – noontz
    Feb 1 at 15:47
  • 1
    @noontz The solution with cert.Verify() did not work in my .NET 7 application, whereas return true worked flawlessly for my development environment.
    – devbf
    Oct 26 at 10:56
57

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
1
  • 2
    wow more then 300 score with only one answer :O Oct 13, 2022 at 7:58
24

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);
}
4
  • 1
    Your, code solved my problem, now its working perfectly in .Net 5 Worker. Thank you very much.
    – agileDev
    Feb 19, 2022 at 13:41
  • 1
    Thank you. Your first piece of code solved the exact SSL issue in my case. Thank you.
    – suma
    Apr 26, 2022 at 4:36
  • 1
    Thank you. it solved my problem in .Net core 6. I add that code in Program.cs file. Aug 13, 2022 at 15:21
  • 3
    Of course this fixes it; it disables SSL verification
    – Zimano
    Jan 4 at 14:48
13

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

2
  • 1
    How to remove the development cert once the SDK has been uninstalled?
    – Aamir
    Mar 28 at 0:09
  • 2
    This answer solved my problem on the production server! Thanks :) Apr 13 at 20:50
9
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

1
8

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);
5

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!

3
  • 2
    I've been using HttpWebRequest for a while now on this server without an issue, and just starting to get the Remote Validation error, even though the app has no validation procedure, it's just a HttpWebRequest. Are you saying the library above gives more information than what HttpWebRequest provides?
    – Dan Chase
    Oct 2, 2021 at 18:33
  • 1
    Hey @DanChase did you update your backend or front end framework version? That’s probably the reason why you’re seeing it. Also it seems like you are using HTTPWebRequest instead of an HTTPclient. I don’t have experience with the former, and the question also uses an httpclient
    – Saamer
    Oct 3, 2021 at 22:41
  • 2
    turned out to be the expired Let's Encrypt Root Certificate that's in the news that caused it, had to remove from the machine. Would have never figured it out, I wish there was some diagnostic with it. I pulled the source on .net mono and looked at the validation, but it didn't really help because it looks like it's just walking up the chain. Removing the expired Root Cert was a hail Mary and it worked. I didn't even see that cert in the chain for the site's cert. Only messed up connecting to itself via FQDN/etc, not to yahoo or google, etc. Scary thing everyone is disabling validation now.
    – Dan Chase
    Oct 5, 2021 at 2:10
4

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

1

This is most likely caused by having your proxy configured incorrectly.

Unfortunately some of the newer Windows workstations are coming with this setup wrong.

Check your system environment variables by running the following script in a Windows command prompt.

Ultimately if your proxy values are configured, but don't have any NO_PROXY settings you are going to encounter issues when trying to reach internal services.

Ultimately I recommend unsetting the HTTP_PROXY and HTTPS_PROXY variables unless you know what they do, and what you need them for.

Also important, check the value of no_proxy and compare it with your co worker to see if there is any differences, sometimes a dot "." can make a difference.

1

Windows 10 add Group Policy configuration for elliptical curves under Computer Configuration > Administrative Templates > Network > SSL Configuration Settings. The ECC Curve Order list specifies the order in which elliptical curves are preferred as well as enables supported curves which are not enabled.

Added support for the following elliptical curves:

 BrainpoolP256r1 (RFC 7027) in Windows 10, version 1507 and Windows Server 2016
    BrainpoolP384r1 (RFC 7027) in Windows 10, version 1507 and Windows Server 2016
    BrainpoolP512r1 (RFC 7027) in Windows 10, version 1507 and Windows Server 2016
    Curve25519 (RFC draft-ietf-tls-curve25519) in Windows 10, version 1607 and Windows Server 2016


reboot machine and success

issues

path set

1

There is a more convenient method to set up a HttpClientHandler with AddHttpClient() method - ConfigurePrimaryHttpMessageHandler(). Reference - https://learn.microsoft.com/en-us/dotnet/core/extensions/httpclient-factory#configure-the-httpmessagehandler

0

If you working in dotnet core (.net core) API or application. Then go to program file or startup class where you are registering DI and register HttpClient along with HttpClientHandler

like below

builder.Services.AddHttpClient("").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler

{ ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; } });

0

For those who are trying to inject IHttpClient to a controller for me the solution was using a named client.

Inside the Program.cs configure the named client:

builder.Services.AddHttpClient("YourNamedClient").ConfigureHttpMessageHandlerBuilder(builder =>
{
    builder.PrimaryHandler = new HttpClientHandler
    {
        ServerCertificateCustomValidationCallback = (m, c, ch, e) => true
    };
});

And inside the controller:

 public class YourController: ControllerBase
    {
        private readonly HttpClient _httpClient;

        public YourController(IHttpClientFactory factory)
        {
            _httpClient = factory.CreateClient("YourNamedClient");
        }

    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.