简体   繁体   English

使用HTTPClient的身份验证处理

[英]Authentication Handling using HTTPClient

I have a class which connects to a Web API, therefore I am initialising a static HTTPClient at top of the class like this 我有一个连接到Web API的类,因此我正在像这样的类顶部初始化一个静态HTTPClient。

private static readonly HttpClient httpClient = new HttpClient();

https://docs.microsoft.com/enus/azure/architecture/antipatterns/improper-instantiation/ 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: 该类中的所有公共方法都使用此HTTPClient来联系API,除login()之外的每个方法都需要一个基本的身份验证标头,该标头应采用以下格式:

Authorization: Basic device_id:X-Secret-Key 授权:基本device_id:X密钥

Where the device_id is a constant for this instance of the class and the secret key a return from the login() method. 其中device_id是该类实例的常数,而私钥是login()方法的返回值。

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. 其中request是正在创建的HTTPRequestMessage,而authInfo是格式为device_id:X-Secret-Key的字符串。

Or should a every method call a seperate HTTPClient from the one used by the Login() function, declared like: 还是每个方法都应从Login()函数使用的方法中调用一个单独的HTTPClient,声明如下:

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

Thank you for any responses 感谢您的任何回应

The Authorization header, add it to the httpClient: Authorization标头,将其添加到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. 添加此标头一次后,应授权以后对WEB API服务的所有调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM