'How to add bearer token authentication to typed HttpClient in Asp.Net Core 6

I'm trying to setup a web api using ASP.Net Core 6 so that users can hit my end points and then I do some work in D365 behind the scenes using a privileged account. I'm using a typed HTTP Client, but I'm not sure how to plugin the bearer authentication so that all the requests from this client have the correct Authorization header attached.

Program.cs

builder.Services.AddHttpClient<D365Service>();

D365Service.cs

private readonly HttpClient httpClient;

public D365Service(HttpClient httpClient)
{
  this.httpClient = httpClient;

  this.httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
  this.httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
  // a whole bunch of other headers
  // Is this where I can add in the bearer Authorization header? How do I generate that token?
}

Any help is appreciated. Thanks.



Solution 1:[1]

To add the token to your httpclinet

you should use the following code

httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue($"Bearer",$"{accessToken}");

How do I generate that token

as @DiplomacyNotWar explained in his comment you should be able to generate that token by following the instructions of the service you are connecting to

Some services will share user name and password ( app Id & secret Key ) and you could use this to set your basic Authentication then you will be able to call your token end point that return the access token that you will be able to use it with your httpclinet

Regards,

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 khaled Dehia