0

I need to access a REST service that has an SSL certificate which isn't really valid. So I added the following in my code:

 System.Net.ServicePointManager.ServerCertificateValidationCallback = 
    ((sender, cert, chain, errors) =>
       cert.Subject.Contains("soap.example.com"));

After that I do what I have to do to send the request to REST service.

Everything is fine.

But lateron I need to connect to a different domain (which has a valid SSL certificate). The the latter fails because of a certificate error that disappears if I restart the IIS and only comes back after the code segment displayed above is called again:

System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

So after sending the request to the REST service with invalid certificate, how can I make sure, the normal behavior is working again?

Simply resetting to ServerCertificateValidationCallback=null does not seem to work.

(I am fully aware about the dangers of the CallBack)

sharptooth
  • 167,383
  • 100
  • 513
  • 979
Ole Albers
  • 8,715
  • 10
  • 73
  • 166
  • Possible duplicate of [How to call default ServerCertificateValidationCallback inside customized validation?](https://stackoverflow.com/questions/28679120/how-to-call-default-servercertificatevalidationcallback-inside-customized-valida) – mjwills Jun 28 '17 at 12:59

1 Answers1

2
System.Net.ServicePointManager.ServerCertificateValidationCallback = 
        ((sender, cert, chain, errors) => 
        errors == SslPolicyErrors.None || cert.Subject.Contains("soap.example.com"));

should do the trick.

mjwills
  • 23,389
  • 6
  • 40
  • 63
  • That looks promising. Will try that. – Ole Albers Jun 28 '17 at 14:12
  • The no-errors check is good. The other side of the or could use some shoring up. The problem being that this would consider `thatsfunny.imnot.soap.example.com` as a valid certificate for `google.com`, since it doesn't assert that `RemoteCertificateNameMatch` isn't set. (And even then things get tricky) – bartonjs Jun 28 '17 at 14:45
  • I agree @bartonjs . Nonetheless, I kept that code to be consistent with the question as asked. – mjwills Jun 28 '17 at 21:41