Search code examples
c#webclientazure-traffic-manager

401 Unauthorized when connecting to API through Azure Traffic Manager in C#


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>

Solution

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

    The answer is detailed here:

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