Setting Authorization Header of HttpClient

前端 未结 21 1888
粉色の甜心
粉色の甜心 2020-11-22 14:53

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 d

相关标签:
21条回答
  • 2020-11-22 15:26

    Using AuthenticationHeaderValue class of System.Net.Http assembly

    public AuthenticationHeaderValue(
        string scheme,
        string parameter
    )
    

    we can set or update existing Authorization header for our httpclient like so:

    httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TokenResponse.AccessToken);
    
    0 讨论(0)
  • 2020-11-22 15:27

    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>();
    }
    
    0 讨论(0)
  • 2020-11-22 15:27

    6 Years later but adding this in case it helps someone.

    https://www.codeproject.com/Tips/996401/Authenticate-WebAPIs-with-Basic-and-Windows-Authen

    var authenticationBytes = Encoding.ASCII.GetBytes("<username>:<password>");
    using (HttpClient confClient = new HttpClient())
    {
      confClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", 
             Convert.ToBase64String(authenticationBytes));
      confClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants.MediaType));  
      HttpResponseMessage message = confClient.GetAsync("<service URI>").Result;
      if (message.IsSuccessStatusCode)
      {
        var inter = message.Content.ReadAsStringAsync();
        List<string> result = JsonConvert.DeserializeObject<List<string>>(inter.Result);
      }
    }
    
    0 讨论(0)
  • 2020-11-22 15:30

    If you want to reuse the HttpClient, it is advised to not use the DefaultRequestHeaders as they are used to send with each request.

    You could try this:

    var requestMessage = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            Content = new StringContent("...", Encoding.UTF8, "application/json"),
            RequestUri = new Uri("...")
        };
    
    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", 
        Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes($"{user}:{password}")));
    
    var response = await _httpClient.SendAsync(requestMessage);
    
    0 讨论(0)
  • 2020-11-22 15:33
    static async Task<AccessToken> GetToken()
    {
            string clientId = "XXX";
            string clientSecret = "YYY";
            string credentials = String.Format("{0}:{1}", clientId, clientSecret);
    
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
                List<KeyValuePair<string, string>> requestData = new List<KeyValuePair<string, string>>();
                requestData.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                FormUrlEncodedContent requestBody = new FormUrlEncodedContent(requestData);
                var request = await client.PostAsync("https://accounts.spotify.com/api/token", requestBody);
                var response = await request.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<AccessToken>(response);
            }
        }
    
    0 讨论(0)
  • 2020-11-22 15:36

    Use Basic Authorization And Json Parameters.

    using (HttpClient client = new HttpClient())
                        {
                            var request_json = "your json string";
    
                            var content = new StringContent(request_json, Encoding.UTF8, "application/json");
    
                            var authenticationBytes = Encoding.ASCII.GetBytes("YourUsername:YourPassword");
    
                            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                   Convert.ToBase64String(authenticationBytes));
                            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                            var result = await client.PostAsync("YourURL", content);
    
                            var result_string = await result.Content.ReadAsStringAsync();
                        }
    
    0 讨论(0)
提交回复
热议问题