2

I trying to authenticate for a simple GET request on the Chargify API. I am probably missing a detail on how to pass the credential to the service.

I got the following error:

"The underlying connection was closed: An unexpected error occurred on a send."

"Authentication failed because the remote party has closed the transport stream."

The code I am using is the following:

const string url = "https://subdomain.chargify.com/subscriptions.json";
var request = (HttpWebRequest)WebRequest.Create(url);

string auth = Convert.ToBase64String(Encoding.ASCII.GetBytes("apikey:x"));
request.Headers[HttpRequestHeader.Authorization] = "Basic " + auth;

WebResponse response = request.GetResponse(); //THROW ERROR

using (Stream responseStream = response.GetResponseStream())
{
    var reader = new StreamReader(responseStream, Encoding.UTF8);
    return reader.ReadToEnd();
}

I am following the instructions on the Chargify API Documentation, you can consult the information here:

https://docs.chargify.com/api-authentication

https://docs.chargify.com/api-introduction

Using the chrome extension "Advanced REST Client", I do a GET request with the url above, then chrome ask for the credential in its traditional popup, I put my api key and 'x' as password, then I get an answer in json for exactly what I am expecting. So I know the api key is correct, the thing I'm missing is how to pass the information in C# through the request.

Using curl in the documentation, they give this example:

 curl -u api-key:x https://subdomain.chargify.com/customers.xml

Do you have any idea, how this -u parameter in curl should be translated in C#?

Thanks!

EDIT As suggested in the comment I tried using the .NET wrapper, but I get the exact error. Here is my code sample:

var _apiConnection = new ChargifyConnect(url, _userName, _password);
var productList = _apiConnection.GetProductList();
jmecwel
  • 75
  • 7

2 Answers2

1

Since the connection is just being closed with no reply, this may be related to the TLS 1.2 requirement that went into effect this week.

https://docs.chargify.com/tls-upgrade-notice

Wendy Smoak
  • 168
  • 5
  • Awesome!! Indeed, adding the following just before creating my request worked: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; – jmecwel Jan 14 '16 at 14:43
  • You can actually just set the `ProtocolType` property on `ChargifyConnect` to the same value - `SecurityProtocolType.Tls12`. It does the same thing, it just calls it right before actually opening the connection, so there's no place for it to get switched back. – djbyter Jan 14 '16 at 15:42
  • @djbyter thanks, good to know I can use the wrapper, it can save a lot of work! – jmecwel Jan 14 '16 at 15:57
0

I fixed this by explicitly setting the TLS version to 1.2. Just add this code before you make any calls to Chargify:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
John B
  • 20,062
  • 35
  • 120
  • 170