使用HTTPClient的身份验证处理 [英] Authentication Handling using HTTPClient

查看:196
本文介绍了使用HTTPClient的身份验证处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接到Web API的类,因此我正在像这样的类顶部初始化一个静态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

private static readonly HttpClient httpClient = new HttpClient();

https://docs.microsoft.com/enus/天蓝色/体系结构/反模式/不正确的示例/

该类中的所有公共方法都使用此HTTPClient来联系API,除login()之外的每个方法都需要一个基本的身份验证标头,该标头应采用以下格式:

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:

授权:基本device_id:X-密钥-

Authorization: Basic device_id:X-Secret-Key

其中device_id是该类实例的常量,而秘密密钥是login()方法的返回.

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)));

其中request是正在创建的HTTPRequestMessage,而authInfo是格式为device_id:X-Secret-Key的字符串.

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

或者,每个方法都应从Login()函数使用的方法中调用一个单独的HTTPClient,声明如下:

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);

谢谢您的回复

推荐答案

Authorization标头,将其添加到httpClient:

The Authorization header, add it to the httpClient:

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

添加此标头一次后,应授权以后对WEB API服务的每次调用.

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

这篇关于使用HTTPClient的身份验证处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆