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:
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: 
My authorization header is {}
Now, when I receive a request from insomnia, for example, I have the following headers:

