HttpClient not sending authorization Bearer token in .Net Core 3.1

I have an ASP.NET Core MVC application that calls an ASP.NET Core WebApi using HttpClient, but I have to send the authorization header, the problem is that my HttpClient won’t send the authorization header.

I have a service for calling the webapi that has the following constructor:

        public ApiService(HttpClient httpClient, IHttpContextAccessor accessor)
        {
            string token = accessor.HttpContext.User.FindFirstValue("JWToken"); // gets user token
            httpClient.BaseAddress = new Uri(AppSettings.BaseUrlApi); //sets the base URL of the webapi
            httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
            httpClient.Timeout = TimeSpan.FromMinutes(1);
            httpClient.DefaultRequestHeaders.Authorization
                         = new AuthenticationHeaderValue("Bearer", token);

            _httpClient = httpClient; // assigns to a private property "private readonly HttpClient _httpClient;"
        }

Then, when I post data to the webapi, I use the following method:

        public async Task<User> PostAsync(string url, User user)
        {
            StringContent jsonContent = new StringContent(
                JsonConvert.SerializeObject(user, Formatting.Indented, _jsonSettings), // _jsonSettings is a JsonSerializerSettings object
                Encoding.UTF8,
                "application/json");

            using HttpResponseMessage httpResponse =
                await _httpClient.PostAsync(url, jsonContent);
            httpResponse.EnsureSuccessStatusCode();
            string responseString = await httpResponse.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<User>(responseString, _jsonSettings);
        }

For requests that do not require an Authorization header, it works pretty fine, but it doesn’t send the Authorization header, I have tried instantiating a new HttClient, using HttpRequestMessage and then SendAsync, but it never works, I also tried using httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); but it doesn’t work, also TryAddWithoutValidation, but doesn’t work.
The worst is, when I check my httpClient object, the authorization token is there:

HttpClient not sending authorization Bearer token in .Net Core 3.1

But then I get a 401 message from my webapi, and when I check the request received in the webapi, the authorization header is empty, and my webapi works fine when it receives requests from ajax calls, or applications like insomnia and postman.

I can’t figure out what I am missing.

EDIT:

In my webapi, the request that’s arriving is:
HttpClient not sending authorization Bearer token in .Net Core 3.1

My authorization header is {}

Now, when I receive a request from insomnia, for example, I have the following headers:

HttpClient not sending authorization Bearer token in .Net Core 3.1

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The code you are using looks as though it should work, I tried something similar on my end and it added the JWT as expected. Is it possible that the 401 is legitimately referring to a bad token? I’d try decoding it with: https://jwt.io/ and validate that all the claims in it make sense (e.g. expiration) and that it is signed correctly.

UPDATE

Adding some code that’s very similar to what you are trying to do that does work for me, FYI this is making a phone call via an API, leaving the JWT generation and command generation out for simplicity

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");

var json = JsonConvert.SerializeObject(command,
    Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
httpClient.DefaultRequestHeaders.Authorization = 
    new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", jwt);

var content = new StringContent(json, Encoding.UTF8, "application/json");

var response = httpClient.PostAsync("https://api.nexmo.com/v1/calls", content).Result;

I can confirm that this most certainly adds the JWT as a bearer token into the header (it would not work otherwise)

hopefully this helps.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x