问题描述
我试图仅将 https 证书验证绕过我们自己的测试环境(多台机器),同时尝试为所有其他连接保持证书验证.
I'm trying to bypass https certificate validation only to our own testing environment (multiple machines), while trying to keep certificate validation for all the other connection.
从在线阅读来看,大多数(如果不是全部)WCF 相关建议似乎都指向以下类似内容
From reading online, most (if not all) WCF related suggestion seems to point to the something similar of following
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
但是,这是一个全局设置,我只想将其应用于特定连接.这是可能/支持的使用场景吗?
However, this is a global setting and I would like to apply this for only a specific connection. Is this even possible/supported usage scenario?
推荐答案
是这样的:
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(ValidateCert);
public static bool ValidateCert(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
string requestHost;
if(sender is string)
{
requestHost = sender.ToString();
}
else
{
HttpWebRequest request = sender as HttpWebRequest;
if(request != null)
{
requestHost = request.Host;
}
}
if(!string.IsNullOrEmpty(requestHost) && requestHost == "my_test_machine")
return true;
return sslPolicyErrors == SslPolicyErrors.None;
}
请注意 文档code>sender 参数:
Note the documentation on the sender
parameter:
传递给 RemoteCertificateValidationCallback 的发送方参数可以是主机字符串名称或派生自 WebRequest(例如 HttpWebRequest)的对象,具体取决于 CertificatePolicy 属性
免责声明 - 我没有测试这个,我是根据文档写的.天啊.
Disclaimer - I didn't test this, I wrote it based on the documentation. YMMV.
这篇关于WCF 每个连接服务器证书验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!