临时禁用证书验证 [英] Temporary disable certificate validation
问题描述
我需要使用Web服务,但是它具有证书,并且需要禁用其身份验证。
I need to consume a web service, but it has a certificate and I need to disable its authentication.
服务器端可以是我们正在使用它来模拟结果的虚拟服务器,也可以是使用安全的肥皂标头的真正的第三方服务器
the server side can be a dummy server that we are using it to "simulate" results OR a real third side server which use secured soap headers
我需要能够在调用虚拟服务器时在服务器中禁用证书验证,但是在调用真实服务器(不是我们的真实服务器)时启用它。
i need to be able to disable the certificate validation in the server when invoking the dummy server, but to enable it when invoking the real server (which is not ours)
我在某个帖子中看到禁用它的方法是这样做:
i saw in some post that the way to disable it is to do this:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
效果很好。
问题是,一旦执行了这一行代码,我似乎就无法逆向它
the problem is that once this line of code is executed i can't seem to "reverse" it
我需要类似以下内容的东西:
i need something like:
if (TestMode)
{
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
}
else
{
//enable certificate validation
}
btw,代码在c#中。
btw, the code is in c#.
任何想法?
推荐答案
您需要注销回调,如下所示:
You need to de-register the callback, something like this:
声明RemoteCertificateValidationCallback引用。
Declare a RemoteCertificateValidationCallback reference.
static RemoteCertificateValidationCallback _callbackTrue;
然后在您的初始化代码中,将其分配为:
Then in your initialization code, assign it like this:
_callbackTrue = (sender, cert, chain, sslPolicyErrors) => true;
然后,当您的TestMode属性更改时,您可以注册/注销回调:
Then you can register / deregister the callback when your TestMode property changes:
// in the setter for TestMode, when set to true.
ServicePointManager.ServerCertificateValidationCallback += _callbackTrue;
// in the setter for TestMode, when set to false
ServicePointManager.ServerCertificateValidationCallback -= _callbackTrue;
只要确保只注册,然后在TestMode从 false变为true时回调即可仅当回调从 true变为 false时才注销。即您的注册/注销应该对称。
Just make sure that you only register then callback when the TestMode goes from 'false to true' and that you only de-register the callback when it goes from 'true to false'. I.e. your registrations / deregistrations should be symmetrical.
这篇关于临时禁用证书验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!