8

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:

enter image description here

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: enter image description here

My authorization header is {}

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

enter image description here

1

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your reply. I check the jwt token and it is valid, the expiration is fine and once I provided the secret token it said Signature Verified. I added the pictures of the requests received from my httpclient (asp.net core) and from insomnia.
@AlefDuarte I added an update which has the exact code I used (which is very similar to yours - that is definitely adding the JWT as a bearer token
I still get the same problem, but since your code should work, now I know it must be some configuration I'm overlooking and not how httpclient is being instantiated. Thank you for your help, If I have any update I'll let you know.
Where is your post data. I want send a post request with bearer token and json at request body. Do not get any proper solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.