简体   繁体   中英

How to start a trusted TLS connection with a server by IP address using HttpClient in C#?

I'm trying to set up a TLS connection to an application running in a (local) VM using C#'s HttpClient on Windows. However, it results in a RemoteCertificateNameMismatch error every time.

This piece of code:

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;

Results in this error:

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)

However, my certificate is valid according to Google Chrome and Mozilla Firefox, but not for Internet Explorer.

Chrome中的有效服务器证书

See the screenshot taken from Chrome. The certificate seems valid. I've created my own Certificate Authority certificate (self signed certificate), then I used that to create my server certificate. I filled in the subject name. As Subject Alternative Name (SAN) I've added the IP address.

Is an IP address field inside the SAN field not supported in IE and HttpClient? If so, is there some other way of validating a server certificate using an IP address?

I'm using dotnet core 2.0.

Reading up on a similar question I found the following:

.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.

You could try using the 'DNS Name' field.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM