Change the security protocol for each request (HttpClient)

I have a web API that needs to communicate with several different services. I currently have the Web API installed to use the following security protocol:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

When the API calls another service through an HttpClient (e.g. Twitter), it will use this protocol. At the same time, however, a different request may be required in order to access something from the cloud, which for some reason requires TLS (and not TLS 1.2). The cloud request before starting sets the security protocol again:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

The problem I am facing is when two separate and unique requests appear: one for Twitter and one for the cloud, the security protocol may switch to the β€œwrong” one before sending it, as a result of which the request will fail.

Is there a way to set the security protocol in HttpClient for each request so that I do not replace the parameter in some singleton somewhere?

+11
c # ssl asp.net-web-api
source share
2 answers

You do not need to install this.

You can use:

 using System.Net; ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; 

Additional notes:

  • Required for .Net 4.5 because Tls12 is not the default protocol.
  • You need to write the above code only once in the application. (For example, in Global.asax> Application_Start in a web application or an analogue in a Winforms application)
  • For .Net 4.6 and higher, Tls12 is the default protocol, so it is not needed
+10
source

There seems to be no way to do this. The SecurityProtocol property is used only inside the TlsStream inner class in one place:

enter image description here

TlsStream seems to support all internal TLS connections such as HTTP, FTP, and SMTP.

I was hoping ServicePoint allows you to customize this. For many settings, ServicePointManager provides only the default value. This hope was unfounded.

So, this is pretty convincing evidence that this is not possible. However, this is not proof.

What should you do? I would disable the HTTP client library for the odd server you're talking to. HTTP is not a particularly complex protocol. I am sure there is another implementation.

Alternatively, use a proxy server that terminates the HTTPS connection on your own server. Then .NET only works with HTTP.

+4
source

All Articles