我正在尝试连接到使用自签名SSL证书的API.我这样做是使用.NET的HttpWebRequest和HttpWebResponse对象.我得到一个例外:
底层连接已关闭:无法为SSL/TLS安全通道建立信任关系.
我明白这意味着什么.我理解为什么 .NET认为它应该警告我并关闭连接.但在这种情况下,无论如何我都想连接到API,中间人攻击会被诅咒.
那么,我该如何为这个自签名证书添加例外呢?或者是告诉HttpWebRequest/Response不要验证证书的方法?我该怎么办?
我需要相信应用程序中的一些自签名证书,所以我覆盖了这样的验证回调:
ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;
...
public static bool MyRemoteCertificateValidationCallback(
Object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
if (IsAprrovedByMyApplication(sender, certificate)) // <-- no matter what the check here is
return true;
else
return false; // <-- here I'd like to call the default Windwos handler rather than returning 'false'
}
Run Code Online (Sandbox Code Playgroud)
但是当出现一些策略错误,并且我连接的站点未被应用程序批准时,将抛出异常.这里的问题是它与标准的Windows行为不同.
考虑一下这个网站:https://www.dscoduc.com/
它的证书有一个未知的发行者,因此不受信任.我已将它与MMC一起添加到Local Copmuter的Trusted People(它是Windows 7).
如果我在不重写证书验证回调的情况下运行此代码:
HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create("https://www.dscoduc.com/");
using (WebResponse resp = http.GetResponse())
{
using (StreamReader sr …Run Code Online (Sandbox Code Playgroud)