Setting Authorization Header of HttpClient

前端 未结 21 1886
粉色の甜心
粉色の甜心 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:11

    this could works, if you are receiving a json or an xml from the service and i think this can give you an idea about how the headers and the T type works too, if you use the function MakeXmlRequest(put results in xmldocumnet) and MakeJsonRequest(put the json in the class you wish that have the same structure that the json response) in the next way

    /*-------------------------example of use-------------*/
    MakeXmlRequest<XmlDocument>("your_uri",result=>your_xmlDocument_variable =     result,error=>your_exception_Var = error);
    
    MakeJsonRequest<classwhateveryouwant>("your_uri",result=>your_classwhateveryouwant_variable=result,error=>your_exception_Var=error)
    /*-------------------------------------------------------------------------------*/
    
    
    public class RestService
    {
        public void MakeXmlRequest<T>(string uri, Action<XmlDocument> successAction, Action<Exception> errorAction)
        {
            XmlDocument XMLResponse = new XmlDocument();
            string wufooAPIKey = ""; /*or username as well*/
            string password = "";
            StringBuilder url = new StringBuilder();
            url.Append(uri);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.ToString());
            string authInfo = wufooAPIKey + ":" + password;
            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            request.Timeout = 30000;
            request.KeepAlive = false;
            request.Headers["Authorization"] = "Basic " + authInfo;
            string documento = "";
            MakeRequest(request,response=> documento = response,
                                (error) =>
                                {
                                 if (errorAction != null)
                                 {
                                    errorAction(error);
                                 }
                                }
                       );
            XMLResponse.LoadXml(documento);
            successAction(XMLResponse);
        }
    
    
    
        public void MakeJsonRequest<T>(string uri, Action<T> successAction, Action<Exception> errorAction)
        {
            string wufooAPIKey = "";
            string password = "";
            StringBuilder url = new StringBuilder();
            url.Append(uri);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.ToString());
            string authInfo = wufooAPIKey + ":" + password;
            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            request.Timeout = 30000;
            request.KeepAlive = false;
            request.Headers["Authorization"] = "Basic " + authInfo;
           // request.Accept = "application/json";
          //  request.Method = "GET";
            MakeRequest(
               request,
               (response) =>
               {
                   if (successAction != null)
                   {
                       T toReturn;
                       try
                       {
                           toReturn = Deserialize<T>(response);
                       }
                       catch (Exception ex)
                       {
                           errorAction(ex);
                           return;
                       }
                       successAction(toReturn);
                   }
               },
               (error) =>
               {
                   if (errorAction != null)
                   {
                       errorAction(error);
                   }
               }
            );
        }
        private void MakeRequest(HttpWebRequest request, Action<string> successAction, Action<Exception> errorAction)
        {
            try{
                using (var webResponse = (HttpWebResponse)request.GetResponse())
                {
                    using (var reader = new StreamReader(webResponse.GetResponseStream()))
                    {
                        var objText = reader.ReadToEnd();
                        successAction(objText);
                    }
                }
            }catch(HttpException ex){
                errorAction(ex);
            }
        }
        private T Deserialize<T>(string responseBody)
        {
            try
            {
                var toReturns = JsonConvert.DeserializeObject<T>(responseBody);
                 return toReturns;
            }
            catch (Exception ex)
            {
                string errores;
                errores = ex.Message;
            }
            var toReturn = JsonConvert.DeserializeObject<T>(responseBody);
            return toReturn;
        }
    }
    }
    
    0 讨论(0)
  • 2020-11-22 15:14

    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

    0 讨论(0)
  • 2020-11-22 15:14

    This is how i have done it:

    using (HttpClient httpClient = new HttpClient())
    {
       Dictionary<string, string> tokenDetails = null;
       var messageDetails = new Message { Id = 4, Message1 = des };
       HttpClient client = new HttpClient();
       client.BaseAddress = new Uri("http://localhost:3774/");
       var login = new Dictionary<string, string>
           {
               {"grant_type", "password"},
               {"username", "sa@role.com"},
               {"password", "lopzwsx@23"},
           };
       var response = client.PostAsync("Token", new FormUrlEncodedContent(login)).Result;
       if (response.IsSuccessStatusCode)
       {
          tokenDetails = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content.ReadAsStringAsync().Result);
          if (tokenDetails != null && tokenDetails.Any())
          {
             var tokenNo = tokenDetails.FirstOrDefault().Value;
             client.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenNo);
             client.PostAsJsonAsync("api/menu", messageDetails)
                 .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
          }
       }
    }
    

    This you-tube video help me out a lot. Please check it out. https://www.youtube.com/watch?v=qCwnU06NV5Q

    0 讨论(0)
  • 2020-11-22 15:14

    BaseWebApi.cs

    public abstract class BaseWebApi
    {
        //Inject HttpClient from Ninject
        private readonly HttpClient _httpClient;
        public BaseWebApi(HttpClient httpclient)
        {
            _httpClient = httpClient;
        }
    
        public async Task<TOut> PostAsync<TOut>(string method, object param, Dictionary<string, string> headers, HttpMethod httpMethod)
        {
            //Set url
    
            HttpResponseMessage response;
            using (var request = new HttpRequestMessage(httpMethod, url))
            {
                AddBody(param, request);
                AddHeaders(request, headers);
                response = await _httpClient.SendAsync(request, cancellationToken);
            }
    
            if(response.IsSuccessStatusCode)
            {
                 return await response.Content.ReadAsAsync<TOut>();
            }
            //Exception handling
        }
    
        private void AddHeaders(HttpRequestMessage request, Dictionary<string, string> headers)
        {
            request.Headers.Accept.Clear();
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
            if (headers == null) return;
    
            foreach (var header in headers)
            {
                request.Headers.Add(header.Key, header.Value);
            }
        }
    
        private static void AddBody(object param, HttpRequestMessage request)
        {
            if (param != null)
            {
                var content = JsonConvert.SerializeObject(param);
                request.Content = new StringContent(content);
                request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            }
        }
    

    SubWebApi.cs

    public sealed class SubWebApi : BaseWebApi
    {
        public SubWebApi(HttpClient httpClient) : base(httpClient) {}
    
        public async Task<StuffResponse> GetStuffAsync(int cvr)
        {
            var method = "get/stuff";
            var request = new StuffRequest 
            {
                query = "GiveMeStuff"
            }
            return await PostAsync<StuffResponse>(method, request, GetHeaders(), HttpMethod.Post);
        }
        private Dictionary<string, string> GetHeaders()
        {
            var headers = new Dictionary<string, string>();
            var basicAuth = GetBasicAuth();
            headers.Add("Authorization", basicAuth);
            return headers;
        }
    
        private string GetBasicAuth()
        {
            var byteArray = Encoding.ASCII.GetBytes($"{SystemSettings.Username}:{SystemSettings.Password}");
            var authString = Convert.ToBase64String(byteArray);
            return $"Basic {authString}";
        }
    }
    
    0 讨论(0)
  • 2020-11-22 15:18

    In the case you want to send HttpClient request with Bearer Token, this code can be a good solution:

    var requestMessage = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        Content = new StringContent(".....", Encoding.UTF8, "application/json"),
        RequestUri = new Uri(".....")
    };
    
    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "Your token");
    
    var response = await _httpClient.SendAsync(requestMessage);
    
    0 讨论(0)
  • 2020-11-22 15:19

    UTF8 Option

    request.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue(
        "Basic", Convert.ToBase64String(
            System.Text.Encoding.UTF8.GetBytes(
               $"{yourusername}:{yourpwd}")));
    
    0 讨论(0)
提交回复
热议问题