无法建立SSL连接

时间:2018-10-22 23:54:44

标签: c# asp.net-core .net-core httpclient splunk-sdk

我在ASP.NET核心应用程序中使用了第三方库(Splunk c# SDK)。我正在尝试通过此SDK连接到我的localhost Splunk服务,但出现异常:

  

System.Net.Http.HttpRequestException:无法建立SSL连接,请参阅内部异常。

内部异常显示:

  

根据验证过程,远程证书无效。

此SDK在后台使用HTTP客户端,但是我无权访问此对象来配置HttpClientHandler。

我在Google上进行的所有搜索最终都使用ServicePointManager绕过了SSL验证,但是该解决方案在Asp.Net核心中不起作用。

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

有什么方法可以绕过asp.Net核心中的此验证?

5 个答案:

答案 0 :(得分:1)

当我在开发人员机器上使用身份服务器(.net core)和 web api(.net core)时,我意识到我需要信任本地主机的 ssl 认证。该命令为我完成了这项工作:

dotnet dev-certs https --trust

答案 1 :(得分:0)

是的,您可以使用以下代码绕过证书...

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

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

答案 2 :(得分:0)

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

这个博客帮助了我

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

答案 3 :(得分:0)

这对我有用,

通过提供自定义的 HttpClientHandler 创建 Splunk.Client.Context ,这将绕过 SSL 无效证书错误。

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

答案 4 :(得分:0)

您收到此错误是因为您的应用程序无法验证连接的证书,并且将其用于创建会话/登录令牌的 API 尤为常见。如上所示,您可以通过一种危险的方式绕过它,但显然这不是一个好的解决方案,除非您只是在进行测试。

最好和最简单的解决方案是使用“modernhttpclient-updated" Nuget package,”,其代码在 this GitHub repo 中共享,其中还有很多文档。

添加 Nuget 包后,将 NativeMessageHandler 传入 HttpClient() 中,如图所示并构建: var httpClient = new HttpClient(new NativeMessageHandler());

现在您将收到一条不同的错误消息,例如`Certificate pinning failure: chain error。 ---> Javax.Net.Ssl.SSLPeerUnverifiedException:主机名 abcdef.ghij.kl.mn 未验证: 证书:sha256/9+L...C4Dw=

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)

请记住,您的其他 API 调用可能不需要这个,并且可能使用不同的主机名,在这种情况下,您也需要将它们注册为 pin,或者只是为它们使用不同的 HttpClient