Problem
I’m using a HttpClient to access a REST API. However, I’m having difficulty configuring the Authorization header. The header must be set to the token I obtained after completing my OAuth request. I came across some.NET code that suggested the following:
httpClient.DefaultRequestHeaders.Authorization = new Credential(OAuth.token);
In WinRT, however, the Credential class does not exist. Anyone know how to change the Authorization header?
Asked by Stephen Hynes
Solution #1
As a result, here’s how to go about it:
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "Your Oauth token");
Answered by Stephen Hynes
Solution #2
request.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"{yourusername}:{yourpwd}")));
Answered by TheWhiteRabbit
Solution #3
I’m seeking for a solid solution to this problem, and I’m asking myself the same question. Hopefully, my response will assist anyone who is experiencing the same issue as me.
using (var client = new HttpClient())
{
var url = "https://www.theidentityhub.com/{tenant}/api/identity/v1";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await client.GetStringAsync(url);
// Parse JSON response.
....
}
reference from https://www.theidentityhub.com/hub/Documentation/CallTheIdentityHubApi
Answered by Willie Cheng
Solution #4
As it is a good practice to reuse the HttpClient instance, for performance and port exhaustion problems, and because none of the answers give this solution (and even leading you toward bad practices 🙁 ), I put here a link towards the answer I made on a similar question :
Here are some resources for learning how to use HttpClient properly:
Answered by Philippe
Solution #5
I have a suggestion for you:
HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");
After that, you can utilize it as follows:
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
responseMessage = await response.Content.ReadAsAsync<ResponseMessage>();
}
Answered by Amankhani MohammadJavad
Post is based on https://stackoverflow.com/questions/14627399/setting-authorization-header-of-httpclient