Search code examples
c#httpwebrequestbasic-authenticationwindows-server-2012-r2

Unable to make HttpWebRequest that is working on Postman


I have a token request that works on Postman on a server.

No body, just basic authentication with username and password:

enter image description here

However, I have this code below that returns the error:

The request was aborted: Could not create SSL/TLS secure channel.

Here is the code below:

string responsedata = string.Empty;

String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
                                
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlToken);                
request.Method = "POST";
request.Headers.Add("Authorization", "Basic " + encoded);
request.PreAuthenticate = true;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
    responsedata = reader.ReadToEnd();
}

What am I doing worng?


Solution

  • I suspect your problem is related to the SecurityProtocol your application runs on. Try running this before your request.

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    

    The endpoint your trying to connect probably requires a higher version of Tls than what your application is providing.

    The default value of this is defined by the system it runs on see: https://learn.microsoft.com/en-us/dotnet/api/system.net.securityprotocoltype?view=net-7.0#system-net-securityprotocoltype-systemdefault

    So when running on an older OS this often is too low for modern API endpoints.

    You can test this by enabling or disabling specific versions of TLS/SSL in Postman, look for "Protocols disabled during handshake" in the settings tab for your request.