1

I have the following code that successfully connects to a third party API in C#:

using (var client = new WebClient())
{
    client.Credentials = new NetworkCredential(login.Username, login.Password);

    var xml = client.DownloadString(url);
    Debug.Write(xml);
}

This works fine when connecting directly to the API. However, I'm trying to utilize Azure Traffic Manager to spread the load to multiple endpoints, and I'm getting 401 Unauthorized exceptions when doing this. It appears to work correctly using tools like Postman and configuring Basic Auth in the request.

I tried to convert the code to RestSharp but it appears to have the same symptoms.

Here are the request from Fiddler using a few different techniques:

C#/WebClient directly to API endpoint (Success)

GET <ApiUrl> HTTP/1.1
Host: <ApiHost>
Connection: Keep-Alive

401 Unauthorized

GET <ApiUrl> HTTP/1.1
Authorization: Basic <AuthToken>
Host: <ApiHost>

C#/WebClient to Azure Traffic Manager (401 Unauthorized)

GET <TrafficManagerApiUrl> HTTP/1.1
Host: <TrafficManagerApiHost>

401 Unauthorized

GET <ApiUrl> HTTP/1.1
Host: <ApiHost>

Postman to Azure Traffic Manager (Success)

GET <TrafficManagerApiUrl> HTTP/1.1
Host: <TrafficManagerApiHost>
Connection: keep-alive
Authorization: Basic <AuthToken>
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Postman-Token: 13396800-33ab-8d7b-664f-68b99e8f4ac1
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8


302 Redirect

GET <ApiUrl> HTTP/1.1
Host: <ApiHost>
Connection: keep-alive
Authorization: Basic <AuthToken>
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Postman-Token: 13396800-33ab-8d7b-664f-68b99e8f4ac1
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: JSESSIONID=<jsessionid>
Mike Cole
  • 14,474
  • 28
  • 114
  • 194
  • 1
    Can you capture the outgoing requests using e.g Fiddler and compare them to the successful Postman requests? – NWard Jun 06 '17 at 14:58
  • @NWard added. If I'd have to venture a guess, when using C#/WebClient through traffic manager it's trying to authenticate to a host different than the original. It seems Postman eagerly sends the Authorization header in the initial request. – Mike Cole Jun 06 '17 at 16:06

1 Answers1

0

I wasn't properly handling the redirect of the Azure Traffic Manager.

The answer is detailed here:

https://stackoverflow.com/a/28671822/86191

Mike Cole
  • 14,474
  • 28
  • 114
  • 194