Dardar
Dardar

Reputation: 751

Temporary disable certificate validation

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; };

which works perfectly.

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, the code is in c#.

any ideas ?

Upvotes: 2

Views: 1109

Answers (1)

user469104
user469104

Reputation: 1236

You need to de-register the callback, something like this:

Declare a RemoteCertificateValidationCallback reference.

static RemoteCertificateValidationCallback _callbackTrue;

Then in your initialization code, assign it like this:

_callbackTrue = (sender, cert, chain, sslPolicyErrors) => true;

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;

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 / de-registrations should be symmetrical)

Upvotes: 4

Related Questions