使用 HttpClient 信任自签名证书

Trusting Self-Signed Certificate using HttpClient

我已经按照 this 教程创建了一个自签名 CA 证书,然后创建了一个基于该 CA 证书的自签名 SSL 证书。然后我在 IIS 中安装了 SSL 证书以通过本地 IP 地址访问我的内部站点,例如10.0.0.1。我想使用 HttpClient 向站点发出如下请求:

using (var httpClient = new HttpClient())
{
    var text = await httpClient.GetStringAsync("https://52.19.32.61:5010");
}

我已将我的自签名 CA 证书添加到本地机器的受信任根证书,但是,我仍然遇到以下异常(任何告诉我关闭 SSL 验证的答案都没有帮助。):

System.Net.Http.HttpRequestException: An error occurred while sending the request. System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

SelfSigned CA 必须在 LocalMachine\Root 存储在服务器和连接到服务器的任何客户端上。

SSL 证书应具有客户端将用于连接到它的确切 DNS 名称。它可以在主题备用名称 (SAN) 扩展中的证书中指定多个 DNS 名称。在您的情况下,您使用的是 IP 地址,因此

  • 您将 IP 地址放在 SAN 中或
  • 您将 IP 地址放入 hosts 文件中,并使用您在颁发 SSL 证书时指定的 DNS 名称,并在 HttpClient 中使用此 DNS 名称

您可以考虑使用 XCA to issue your certificates. It has nice GUI and is built on top of OpenSSL. It has predefined templates for CA and SSL server. More info in documentation here