Setting Authorization Header of HttpClient

938,503

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:

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>();
}
Share:
938,503
Stephen Hynes
Author by

Stephen Hynes

Updated on January 27, 2022

Comments

  • Stephen Hynes
    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
    Jean Hominal almost 10 years
    He is using HttpClient, not WebClient.
  • Raffaeu
    Raffaeu over 9 years
    This is not working, if you inspect the Auhtorization header is does not contains anything more than a string Basic.
  • SomethingOn
    SomethingOn over 8 years
    I'm doing the exact same thing @willie and I'm still getting a 401 from my API
  • Willie Cheng
    Willie Cheng over 8 years
    Hi @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
    Jonathan Wood over 7 years
    Can 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
    Secret Squirrel almost 7 years
    how do you get "Your Oauth token"?
  • Richard
    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
    Red almost 7 years
    What I've used is: client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "encrypted user/pwd"); Taking encrypted user/pwd from Advanced Rest Client chrome extension.
  • n00b
    n00b almost 7 years
    @Red fyi, the second parameter is the base64 encoded user:password (its not encrypted).
  • crush
    crush about 6 years
    Is 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
    Pavel Chuchuva about 6 years
    Beware: this might result in ArgumentNullException, see stackoverflow.com/a/47975423/14131
  • ProgrammingLlama
    ProgrammingLlama about 6 years
    You 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
    Craig almost 6 years
    My 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
    Craig almost 6 years
    Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'System.Net.Http.Headers.AuthenticationHeaderValue.Authentic‌​ationHeaderValue(str‌​ing, string)' has some invalid arguments
  • Jonathan Allen
    Jonathan Allen over 5 years
    You shouldn't put an HttpClient in a using block. (Yes, I know it sounds backwards, but you'll leak connections if you use using instead of just recycling the HttpClient.)
  • Jonathan Allen
    Jonathan Allen over 5 years
    The port exhaustion problem is no joke. It almost never happens in QA, but will hit any heavily used project in production.
  • RyanOC
    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
    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
    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
    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
    David Klempfner over 4 years
    System.Text.ASCIIEncoding.ASCII is actually in the parent class Encoding. So you can use System.Text.Encoding.ASCII instead.
  • jtate
    jtate over 4 years
    Welcome 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
    ViRuSTriNiTy over 4 years
    First example does not work as SetBasicAuthentication() is not available by default so it has to be a extension method. Where is it defined?
  • Najeeb
    Najeeb over 4 years
    What if there are two tokens that I need to pass?
  • emp
    emp over 4 years
    See my post for a concrete example stackoverflow.com/a/59052193/790635
  • Johan Franzén
    Johan Franzén almost 4 years
    If 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
    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 the HttpClient.
  • Dinoel Vokiniv
    Dinoel Vokiniv over 2 years
    Yeah, 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
    motevalizadeh over 2 years
    What is "model" in your code?
  • Sumesh Es
    Sumesh Es about 2 years
    @SecretSquirrel var token = await HttpContext.GetTokenAsync("access_token");
  • Will Huang
    Will Huang about 2 years
    @ViRuSTriNiTy Install the IdentityModel package first, then using IdentityModel.Client;.
  • Joshua Enfield
    Joshua Enfield almost 2 years
    Also 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.)