向标头添加授权
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了向标头添加授权相关的知识,希望对你有一定的参考价值。
我有以下代码:
...
AuthenticationHeaderValue authHeaders = new AuthenticationHeaderValue("OAuth2", Contract.AccessToken);
string result = await PostRequest.AuthenticatedGetData(fullUrl, null, authHeaders);
return result;
...
public static async Task<string> AuthenticatedGetData(string url, FormUrlEncodedContent data, AuthenticationHeaderValue authValue)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authValue.Parameter);
HttpResponseMessage response = await client.PostAsync(new Uri(url), data);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
响应=等待部分只是继续循环,没有任何反应。我有什么想法我做错了吗?
问题是,我如何发送以下标题:
Authorization: OAuth2 ACCESS_TOKEN
到外部网络api
这条线
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(authValue.Parameter);
将生成此标头值
Authorization: ACCESS_TOKEN
其中ACCESS_TOKEN
是authValue.Parameter
的值。您想要分配您传递的值以获取所需的标头
client.DefaultRequestHeaders.Authorization = authValue;
会生产
Authorization: OAuth2 ACCESS_TOKEN
我为此苦苦挣扎。我一直收到错误说“格式无效”,因为我有一个自定义实现,并且Authorization标头针对某些标准进行了验证。然而,以这种方式添加标题有效:
var http = new HttpClient();
http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=XXX");
获取AuthenticationHeaderValue以处理我的请求时遇到类似问题。我也在使用GitHub的JWT JsonWebToken。我能够从API获取令牌,但很难在其他GET和POST中使用它。
var jwt = JsonWebToken.Encode(token, APISECRET, JwtHashAlgorithm.HS256);
var tk = GetTokenFromApi(); // basically returns an encrypted string.
手动使用WebRequest:哪个工作正常。
request.ContentType = "application/json";
request.Method = "POST";
request.Headers.Set("Authorization", string.Format("Bearer {0}", tk));
当我们切换到HttpClient并使用AuthenticationHeaderValue时,无法弄清楚如何正确设置它。查看请求字符串后,我看到它为我添加了“授权”。玩弄参数,这最终有效。
var authenticationHeaderValue = new AuthenticationHeaderValue("Bearer", tk);
也许对其他人有意义。因为我搜索了很长时间。但您也必须保存您的cookie,并在下次请求时提供。首先,这是我如何获得我的身份验证代码并将我的cookie保存在静态变量中(在我第一次调用此方法时,我给令牌一个空值)。
public static CookieContainer CookieContainer;
public static async Task<string> Post<TRequest>( TRequest requestBody, string path, string token = "")
{
var baseUrl = new Uri($"urlFromApi");
CookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = CookieContainer })
using(var client = new HttpClient(handler){BaseAddress = baseUrl})
{
client.DefaultRequestHeaders.ConnectionClose = false;
if (!string.IsNullOrWhiteSpace(token))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{token}");
}
ServicePointManager.FindServicePoint(client.BaseAddress).ConnectionLeaseTimeout = 60 * 1000; //1 minute using (var content = new ByteArrayContent(GetByteData(requestBody)))
using (var content = new ByteArrayContent(GetByteData(requestBody)))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync(String.Empty, content);
return await GetResponseContent(response);
}
}
}
在此之后,如果我对api做任何请求,我包括cookie(令牌就是你从第一个响应得到的结果)public static async Task Get(string path,string token =“”){
var baseUrl = $"https://innoviris-ai.collibra.com/rest/2.0{path}";
using (var handler = new HttpClientHandler() { CookieContainer = CookieContainer })
using (var client = new HttpClient(handler) {BaseAddress = new Uri(baseUrl)})
{
client.DefaultRequestHeaders.ConnectionClose = false;
if (!string.IsNullOrWhiteSpace(token))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{token}");
}
ServicePointManager.FindServicePoint(client.BaseAddress).ConnectionLeaseTimeout = 60 * 1000; //1 minute
var response = await client.GetAsync(String.Empty);
return await GetResponseContent(response);
}
}
以上是关于向标头添加授权的主要内容,如果未能解决你的问题,请参考以下文章