Search code examples
c#restxamarinbasic-authenticationdotnet-httpclient

Authorization Header not sent through an HttpClient request


Context

I want to make a simple API call with Basic authentication, using the HtppClient, in a Xamarin app.

Problem

I have been doing it with no problem for a while, but since a few days, it seems not to work anymore. No matter if I checkout previous commits or not. This request does work with Postman ofc, so I'm sure it comes from my code somewhere, and not the API.

I tried targeting both .Net Standard 2.0 or 2.1 and no matter what I do, API tells me I lack Authorization header. I even tried to display myClient.DefaultRequestHeaders.Authorization before the request (authorization is there and correct) and reponse.RequestMessage.Headers after the request (Authorization is lacking, other headers are present).

Code Samples

Here is my initialization of the client :

HttpClient _clientNewApi = new HttpClient();
string authDataNewApi = string.Format("{0}:{1}", username, password);
string authHeaderValueNewApi = Convert.ToBase64String(Encoding.UTF8.GetBytes(authDataNewApi));
_clientNewApi.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValueNewApi);
_clientNewApi.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

And here is the code making the request:

Uri uri = new Uri(recieved_uri);
// _clientNewApi.DefaultRequestHeaders.Authorization is well set
HttpResponseMessage json_response = await _clientNewApi.GetAsync(uri);
// json_response.RequestMessage.Headers does not contain Authorization Header
// json_response.StatusCode is Unauthorized, and the message sent back by the API is "No authentication credentials provided."

I've been desperately looking at my code and doing checkouts to no avail for hours guys, any clue rly appreciated :)


Solution

  • A bit late reply, but my problem came from the API that was sending redirect code (3XX).

    Postman does the redirection without saying anything which is the reason I never saw it.

    That code was handled automatically by the HttpClient as well but the Authorizations Headers were not transmitted to the redirected request (Security reason I guess). I had to disable to automatic redirection in order to handle it myself and pass the Headers to the second request.