如何在自定义验证中调用默认的ServerCertificateValidationCallback?

时间:2015-02-23 17:00:01

标签: c# .net ssl certificate

我想修改.Net的默认ServerCertificateValidationCallback以验证我公司的一些证书,但保留其他证书的默认验证。

我似乎无法这样做,因为默认的ServerCertificateValidationCallback值为空。

ServicePointManager.ServerCertificateValidationCallback = 
(sender, certificate, chain, sslPolicyErrors) => 
 validCertificatesSerialNumbers.Contains(certificate.GetSerialNumberString()) ||    
 defaultlCallback.Invoke(sender, certificate, chain, sslPolicyErrors) //How do I set defaultCallback?
;

谢谢

1 个答案:

答案 0 :(得分:12)

从我在reference source中可以看出,这是回调发挥作用的地方:

if (ServicePointManager.ServerCertificateValidationCallback != null)
{
    useDefault = false;
    return ServicePointManager.ServerCertValidationCallback.
                               Invoke(m_Request,
                                      certificate,
                                      chain,
                                      sslPolicyErrors);
}

if (useDefault)
    return sslPolicyErrors == SslPolicyErrors.None;

这意味着已经执行了验证并知道它是否通过您只需要检查sslPolicyErrors参数。你会这样做:

ServicePointManager.ServerCertificateValidationCallback = 
(sender, certificate, chain, sslPolicyErrors) => 
validCertificatesSerialNumbers.Contains(certificate.GetSerialNumberString()) || (sslPolicyErrors == SslPolicyErrors.None);