错误信息
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”。
原因
证书中没有列出这个主机名
常见SAN 列表中缺少新的子域名、环境名称或裸域名。
通过 IP 地址、localhost 或容器别名连接
常见为公共名称签发的证书中,不包含 docker-compose 或 Kubernetes 中的服务名称,也不包含直接使用的 IP 地址。
在 Encrypt=True 时通过 IP 或别名连接 SQL Server
偶见Microsoft.Data.SqlClient 默认会验证服务器证书(从版本 4 起默认 Encrypt=True);如果服务器证书中写的是 FQDN,而你通过 IP 或短名称连接,名称检查就会失败。
修复方法
- 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.
使用证书中的名称连接
修改 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.
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;