c# - 如何在 C# 中使用 HttpClient 通过 IP 地址启动与服务器的可信 TLS 连接?

标签 c# .net ssl .net-core

我尝试在 Windows 上使用 C# 的 HttpClient 建立与在(本地)VM 中运行的应用程序的 TLS 连接。但是,它每次都会导致 RemoteCertificateNameMismatch 错误。

这段代码:

HttpClientHandler handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, policyErrors) =>
{
    Console.WriteLine($"Policy Errors: {policyErrors}");
    return policyErrors == SslPolicyErrors.None;
};
HttpClient httpClient = new HttpClient(handler)
{
    BaseAddress = new Uri("https://192.168.99.100/engine-rest")
};
var result = httpClient.GetAsync("/engine").Result;

导致此错误:

Policy Errors: RemoteCertificateNameMismatch

Unhandled Exception: System.AggregateException: One or more errors occurred. (An error occurred while sending the request.) ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.WinHttpxception: A security error occurred
   at System.Net.Http.WinHttpRequestCallback.OnRequestSendingRequest(WinHttpRequestState state)
   at System.Net.Http.WinHttpRequestCallback.RequestCallback(IntPtr handle, WinHttpRequestState state, UInt32 internetStatus, IntPtr statusInformation, UInt32 statusInformationLength)

但是,根据 Google Chrome 和 Mozilla Firefox,我的证书有效,但不适用于 Internet Explorer。

Valid server certificate in Chrome

查看从 Chrome 截取的屏幕截图。该证书似乎有效。我已经创建了我自己的证书颁发机构证书(自签名证书),然后我用它来创建我的服务器证书。我填写了主题名称。作为主题备用名称 (SAN),我添加了 IP 地址。

IE和HttpClient不支持SAN字段里面的IP地址字段吗?如果是这样,是否有其他方法可以使用 IP 地址验证服务器证书?

我正在使用 dotnet core 2.0。

最佳答案

阅读类似的问题,我发现了以下内容:

.NET does not support IP addresses as Subject Alternative Names directly because it relies on Schannel to do the verification of the IP address in the cert.

Schannel only looks for the hostname (IP) given in the https request among the "DNS Name=" fields of the cert. So if you could get a CA to give you a cert with the IP addresses listed in the "DNS Name=" fields then it would probably work.

您可以尝试使用“DNS 名称”字段。

来源:Does .NET web service client support SSL cert with IP in Alternate Subject Name

关于c# - 如何在 C# 中使用 HttpClient 通过 IP 地址启动与服务器的可信 TLS 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49113544/

相关文章:

c# - 防止重复的 MDI 子窗体

c# - 我应该使用 ToString() 还是 GetDateTimeFormats() 来格式化 DateTime?

c# - 具有继承变化的DataContract

java - 保护 Android 应用程序免受网络嗅探

java - 添加/代替 SSL 的 SSO

c# - 异步服务器套接字多个客户端

c# - 如何将 ViewModel 属性验证与 ViewModel 分离?

c# - Syncfusion 图表轨迹球风格

.net - 在 TabControl 的第一个和最后一个可见 TabItem 上设置样式

oracle - 数据库服务器 TLS 配置。故障 TNS-00542 : SSL Handshake failed