Authorization Header of HttpClient Not Being Passed

44 views Asked by At

I've looked at multiple posts about this and none of the solutions that I see seem to work in my case.

var request = new HttpRequestMessage(HttpMethod.Post, _Endpoint);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("APIToken", _apiKey);
//request.Headers.Add("Authorization APIToken", _apiKey);
request.Content = new StringContent(JsonSerializer.Serialize(contacts))
{
    Headers =
    {
        ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json")
    }
};

using (var response = await _client.SendAsync(request))
{
    var readstring = response.Content.ReadAsStringAsync().Result;
    ...
}

The request.Headers.Add is commented out because I tried to do it that way initially.

I also set DefaultRequestHeader when creating _client:

_client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("APIToken", _apiKey);

It runs in Postman with the header parameter set as:

Authorization: APIToken [APIKey]

When I set a breakpoint just before calling SendAsync I can see that the correct values are loaded for the Authorization headed.

enter image description here

But I get the error message from the server that says:

"Authentication credentials were not provided."

There's a different message returned if I enter the wrong APIKey in Postman which tells me that it's not sending incorrect credentials, it isn't sending the authorization header at all.

1

There are 1 answers

0
NomadicDeveloper On

It was being redirected and the authorization token was not being passed during the redirect. I had to point to the final url in order to get it to work.