Setting Authorization Header of HttpClient
Solution 1
So the way to do it is the following,
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "Your Oauth token");
Solution 2
request.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"{yourusername}:{yourpwd}")));
Solution 3
I look for a good way to deal with this issue and I am looking at the same question. Hopefully, this answer will be helping everyone who has the same problem likes 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
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 :
https://stackoverflow.com/a/40707446/717372
Some sources on how to use HttpClient the right way:
- https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
- https://blogs.msdn.microsoft.com/alazarev/2017/12/29/disposable-finalizers-and-httpclient/
Solution 5
I suggest to you:
HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");
And then you can use it like that:
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
responseMessage = await response.Content.ReadAsAsync<ResponseMessage>();
}
Stephen Hynes
Updated on January 27, 2022Comments
-
Stephen Hynes over 2 years
I have an HttpClient that I am using for a REST API. However I am having trouble setting up the Authorization header. I need to set the header to the token I received from doing my OAuth request. I saw some code for .NET that suggests the following,
httpClient.DefaultRequestHeaders.Authorization = new Credential(OAuth.token);
However the Credential class does that not exist in WinRT. Anyone have any ideas how to set the Authorization header?
-
Jean Hominal almost 10 yearsHe is using
HttpClient
, notWebClient
. -
Raffaeu over 9 yearsThis is not working, if you inspect the Auhtorization header is does not contains anything more than a string Basic.
-
SomethingOn over 8 yearsI'm doing the exact same thing @willie and I'm still getting a 401 from my API
-
Willie Cheng over 8 yearsHi @SomethingOn I think you didn't get a correct token key ,so that you got 401 , I will share my way on my personal "Ask Question" , hopefully it can help you to deal with your problem.PS waiting for a moment
-
Jonathan Wood over 7 yearsCan anyone explain why it's important to convert the username and password to a base64 string? It offers no real encryption, so why does that matter?
-
Secret Squirrel almost 7 yearshow do you get "Your Oauth token"?
-
Richard almost 7 years@JonathanWood Because that;s how it is defined to be used. Basic offers no encryption, just enough encoding to avoid issues with choice of password characters in a header.
-
Red almost 7 yearsWhat I've used is:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "encrypted user/pwd");
Taking encrypted user/pwd from Advanced Rest Client chrome extension. -
n00b almost 7 years@Red fyi, the second parameter is the base64 encoded user:password (its not encrypted).
-
crush about 6 yearsIs there any particular reason you used ASCII encoding here? I assume there is no issue with using UTF8 encoding since we are Base64 encoding it anyways. I guess I'm wondering if the Basic authentication specification says that the username:password combo should be in ASCII only?
-
Pavel Chuchuva about 6 yearsBeware: this might result in ArgumentNullException, see stackoverflow.com/a/47975423/14131
-
ProgrammingLlama about 6 yearsYou shouldn't include code to disable checking of SSL certificates in an example like this. People may blindly copy your code not realising what it does. I've removed those lines for you.
-
Craig almost 6 yearsMy application was happily using this for ages, then out of the blue I started getting a RuntimeBinderException. I had to switch to httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer", "Your Oauth token"); to get it going again.
-
Craig almost 6 yearsMicrosoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'System.Net.Http.Headers.AuthenticationHeaderValue.AuthenticationHeaderValue(string, string)' has some invalid arguments
-
Jonathan Allen over 5 yearsYou shouldn't put an HttpClient in a
using
block. (Yes, I know it sounds backwards, but you'll leak connections if you useusing
instead of just recycling the HttpClient.) -
Jonathan Allen over 5 yearsThe port exhaustion problem is no joke. It almost never happens in QA, but will hit any heavily used project in production.
-
RyanOC over 5 years@kraeg same thing happened to me. Switching worked, but I found out that my authtoken was a jobject and the fix you mentioned must have cast it correctly. When I properly cast the jobject to a string the original method worked again.
-
TroySteven about 5 years@kraeg, the code you listed doesn't compile, did you mean to concatenate the last 2 strings like so: client.DefaultRequestHeaders.Add("Authorization", "Bearer " + "Your Oauth token");
-
Craig about 5 years@matwonk I reckon you must be right. I can't find that piece of code anywhere, but I do find plenty of the concatenated version. Sorry about that.
-
Bondolin almost 5 years@crush See stackoverflow.com/a/7243567/1399272. It seems like UTF-8 is a valid option going forward (i.e. modern browsers [i.e. not IE])
-
David Klempfner over 4 yearsSystem.Text.ASCIIEncoding.ASCII is actually in the parent class Encoding. So you can use System.Text.Encoding.ASCII instead.
-
jtate over 4 yearsWelcome to stackoverflow. In addition to the answer you've provided, please consider providing a brief explanation of why and how this fixes the issue.
-
ViRuSTriNiTy over 4 yearsFirst example does not work as
SetBasicAuthentication()
is not available by default so it has to be a extension method. Where is it defined? -
Najeeb over 4 yearsWhat if there are two tokens that I need to pass?
-
emp over 4 yearsSee my post for a concrete example stackoverflow.com/a/59052193/790635
-
Johan Franzén almost 4 yearsIf your token times out every 1h for example then you have to update the HttpClient with this solution. I would suggest checking that your token is still valid and otherwise refreshing it and adding it to the HttpRequestMessage
-
masiton over 3 years@JonathanAllen if you're referring to connection leak described here, it may be worth noting that few readers have mentioned in article comments that the leak might be related to how responses are handled, since many developers forget to dispose the
HttpResponse
itself and only dispose of theHttpClient
. -
Dinoel Vokiniv over 2 yearsYeah, surprisingly hard to find this answer. I guess many don't read the docs much because best practice is to have HttpClient be a static member variable to avoid port exhaustion issues. And then it makes little sense to use DefaultRequestHeaders either, especially if we're talking token/bearer authentication like many do here because these tokens will inevitably expire! So basing a default on that is just backwards.
-
motevalizadeh over 2 yearsWhat is "model" in your code?
-
Sumesh Es about 2 years@SecretSquirrel var token = await HttpContext.GetTokenAsync("access_token");
-
Will Huang about 2 years@ViRuSTriNiTy Install the
IdentityModel
package first, thenusing IdentityModel.Client;
. -
Joshua Enfield almost 2 yearsAlso note that
client.DefaultRequestHeaders.Add
will throw an exception if you end up calling it multiple times with the same header name. (Trying to add same header multiple times.)