Authentication Handling using HTTPClient

自古美人都是妖i 提交于 2019-12-13 03:49:35

问题


I have a class which connects to a Web API, therefore I am initialising a static HTTPClient at top of the class like this

private static readonly HttpClient httpClient = new HttpClient();

https://docs.microsoft.com/enus/azure/architecture/antipatterns/improper-instantiation/

This HTTPClient is used by all public methods within the class to contact the API, each method except login() requires a basic authentication header, this header should be in the format:

Authorization: Basic device_id:X-Secret-Key

Where the device_id is a constant for this instance of the class and the secret key a return from the login() method.

Therefore should every method contain:

request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo)));

Where request is the HTTPRequestMessage being created and authInfo is a string in the format device_id:X-Secret-Key.

Or should a every method call a seperate HTTPClient from the one used by the Login() function, declared like:

var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential (device_id, secret_key);
var client = new HttpClient (handler);

Thank you for any responses


回答1:


The Authorization header, add it to the httpClient:

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo)));

After you add this header ONCE, every future calls to the WEB API service should be authorized.



来源:https://stackoverflow.com/questions/45609530/authentication-handling-using-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!