跳到主要内容
ecdsa.com
.NET SslStream / HttpClient.NET

错误信息

The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch

也可能输出为

  • The remote certificate is invalid according to the validation procedure.

较旧的 .NET 版本只打印“The remote certificate is invalid according to the validation procedure.”,不指明具体错误;当前的 .NET 会附加 SslPolicyErrors 的值。HttpClient 会把它包装在外层异常“The SSL connection could not be established, see inner exception.”中。

.NET SslStream / HttpClient — SslPolicyErrors.RemoteCertificateNameMismatch

含义

服务器的证书链是受信任的,但 .NET 所连接的主机名不在该证书签发时所针对的名称范围内,即不在其主题备用名称(SAN)之中。“according to the validation procedure”这一措辞用于名称不匹配之类的 SslPolicyErrors,而信任和日期问题使用的是“errors in the certificate chain”。

原因

修复方法

  1. 1.

    将证书中的名称与 URL 比较

    打印服务器实际发送的证书的 SAN 列表。

    bash
    echo | openssl s_client -connect api.example.com:443 -servername api.example.com 2>/dev/null \
      | openssl x509 -noout -subject -ext subjectAltName
  2. 2.

    使用证书中的名称连接

    修改 URL 和名称解析,而不是关闭验证。

    csharp
    // Use a host name from the certificate in the URL (resolve it to the address you need via DNS)
    using var client = new HttpClient();
    var response = await client.GetAsync("https://www.example.com/health");
  3. 3.

    SQL Server:设置 HostNameInCertificate

    Microsoft.Data.SqlClient 5.0 及更高版本接受 HostNameInCertificate,这样你可以通过地址连接,同时仍按证书的真实名称进行验证;而 TrustServerCertificate=True 会跳过所有验证,除了用完即弃的临时环境之外不应使用。

    text
    # Microsoft.Data.SqlClient: connect by IP/alias but validate against the certificate's name
    Server=10.0.0.5;Database=app;Encrypt=True;HostNameInCertificate=sql01.corp.example.com;

相关错误

浏览完整的签名错误库