You can add a JWT bearer token to a request by adding it to the Authorization
header with a bearer
scheme in front of the token value. The syntax of a Authorization header is the following:
Authorization: <auth-scheme> <authorization-parameters>
For a JWT token this would be:
Authorization: bearer eyThisIsYourToken..
In C# you can add the authorization header with a bearer token for a single request using the following:
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("/someUrl")
};
//this
requestMessage.Headers.Authorization
= new AuthenticationHeaderValue("Bearer", "eyThisIsYourToken..");
var response = await httpClient.SendAsync(requestMessage);
In the above we create a HttpRequestMessage
, we then add the Authorization
header using .Headers.Authorization
with the auth scheme "Bearer" and the value "eyThisIsYourToken.." which is our token. We then use SendAsync
to send the request. You have now sent a HTTP request with a JWT bearer token.
Alternatively to setting the JWT token per request, you can set it as a default header on your HttpClient
:
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "eyThisIsYourToken..");
Using DefaultRequestHeaders
you can set headers for all requests created using that HttpClient
instance.
I hope you found this helpful, feel free to leave a comment down below!