bliulinx
bliulinx

Reputation: 23

HTTP GET request authorization header is not set for some requests

I'm trying to use this code to send a GET HTTP request to some resource over https. The request must include the Authorization header with the Basic scheme in order to be authenticated:

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

using (var client = new HttpClient())
{
    string credentials = "dXNlcm5hbWU6cGFzc3dvcmQ=";
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
    client.DefaultRequestHeaders
        .Accept
        .Add(new MediaTypeWithQualityHeaderValue("application/json"));

    string jsonResponse = await client.GetStringAsync(uri);

    return jsonResponse;
}

The problem I'm facing is that when I make the request for that url, I get a 401 Unauthorized response. Looking at the request with Fiddler shows that there is no Authorization header set on the request.

The authorization header gets through if I make the request towards a mock server such as Request Bin, for instance.

I thought that maybe there is a proxy server in between removing my authorization header for that particular resource I am asking. But making the "same" HTTP request using Postman from the same machine is successful.

Any ideas about what could be removing the Authorization header when making the request from C#? Thanks in advance!

Upvotes: 0

Views: 1287

Answers (1)

bliulinx
bliulinx

Reputation: 23

Figured out what was the problem in the end.

Some servers respond with a 302 (redirect) when there is a missing slash at the end for instance, like it was in my case. Combining that with the fact that HTTPS strips out the Authorization header between 3xx requests, the second request to the server (with the slash) did not contain the Authorization header, hence the 401.

Upvotes: 1

Related Questions