iamlawrencev
iamlawrencev

Reputation: 158

HttpClient not accepting Authorization headers (401 Unauthorized)?

I am creating a Xamarin.Forms mobile app that targets Android with .NET Standard as my code sharing method. Unfortunately the API I'm consuming works in Postman but doesn't work in C# using HttpClient from System.Net.Http.

Postman request works using this header:

Request Screenshot

I have tried 3 different approaches but they all still return "401 unauthorized". I've also checked the INTERNET permission in my Android Manifest file.

HttpClient.DefaultRequestHeaders.Add("Authorization", "Token e2eeb1aa9f32eb0ekgn353b6fadb772");
HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", "e2eeb1aa9f32eb0ekgn353b6fadb772");
HttpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Token e2eeb1aa9f32eb0ekgn353b6fadb772");

Upvotes: 4

Views: 10549

Answers (4)

Samy Casas
Samy Casas

Reputation: 1

The url I was calling was "http" and the server redirects it to https. Apparently this drops the headers. Didnt happen through postman !!

Solution: use httpS

Upvotes: 0

dush88c
dush88c

Reputation: 2106

Please make sure your HTTP request URL is correct or not. Sometimes you may need a trailing forwardslash ( '/' ). If you missed it in HTTP client, will not work but POSTMAN will .

Upvotes: 11

Fidel Orozco
Fidel Orozco

Reputation: 1046

In my case, was fixed when I set the basic authentication in the AuthenticationHeaderValue.

var authToken = Encoding.ASCII.GetBytes(_UserName + ":" + _Password);
client.DefaultRequestHeaders.Authorization= new AunthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));

Upvotes: 0

Try setting the header on the HttpRequestMessage:

request.Headers.Authorization = new 
    AuthenticationHeaderValue("Bearer","e2eeb1aa9f32eb0ekgn353b6fadb772");

Upvotes: 3

Related Questions