我有一个HttpClient,用于访问REST API。但是我在设置Authorization头时遇到了问题。我需要将头设置为从OAuth请求中收到的令牌。
我看到了一些.NET的代码,建议如下操作:
httpClient.DefaultRequestHeaders.Authorization = new Credential(OAuth.token);
然而,在WinRT中没有Credential类。有没有任何想法如何设置Authorization头?
我有一个HttpClient,用于访问REST API。但是我在设置Authorization头时遇到了问题。我需要将头设置为从OAuth请求中收到的令牌。
我看到了一些.NET的代码,建议如下操作:
httpClient.DefaultRequestHeaders.Authorization = new Credential(OAuth.token);
然而,在WinRT中没有Credential类。有没有任何想法如何设置Authorization头?
因此,实现这个的方法如下所示:
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "Your Oauth token");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "加密后的用户名/密码");
我从Chrome扩展程序Advanced Rest Client中获取了加密后的用户名/密码。 - Redrequest.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"{yourusername}:{yourpwd}")));
我正在寻找解决这个问题的好方法,也在考虑同样的问题。希望这个答案能够帮助像我一样有相同问题的每个人。
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.
....
}
参考自https://www.theidentityhub.com/hub/Documentation/CallTheIdentityHubApi
HttpResponse
本身,只处理了HttpClient
。 - masitonclient.DefaultRequestHeaders.Add
,它将抛出异常。(尝试添加多个相同的标头。) - Joshua EnfieldHttpClient
放入 using
语句中,因为这最终会导致套接字耗尽问题。原因在于:https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong - Tony由于性能和端口耗尽问题,重用HttpClient实例是一个好的做法。因为没有任何答案提供这个解决方案(甚至会引导您走向不良实践:(),所以我在这里放置一个链接,指向我在类似问题上的答案:
https://dev59.com/Y10a5IYBdhLWcg3w6sZk#40707446
以下是一些正确使用HttpClient的资源:
HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");
然后你可以像这样使用它:
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
responseMessage = await response.Content.ReadAsAsync<ResponseMessage>();
}
HttpClient
请求,这段代码可能是一个不错的解决方案: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);
我正在设置令牌
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
它在一个端点上工作,但在另一个端点上不工作。问题是我在"bearer"上使用了小写字母b。更改后,现在两个API都可以正常运行。如果您甚至没有考虑它作为查找针的干草堆之一,那么很容易错过这样的问题。
请确保使用大写字母的"Bearer"
。
使用基本身份验证和JSON参数。
using (HttpClient client = new HttpClient())
{
var request_json = "your json string";
var content = new StringContent(request_json, Encoding.UTF8, "application/json");
var authenticationBytes = Encoding.ASCII.GetBytes("YourUsername:YourPassword");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authenticationBytes));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var result = await client.PostAsync("YourURL", content);
var result_string = await result.Content.ReadAsStringAsync();
}
HttpClient
放入 using
语句中,因为这最终会导致套接字耗尽问题。原因在于:https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong - Tony对于现在(2021年)找到这个旧帖子的任何人,请查看有关HttpClientFactory的文档,该文档介绍了可注入的HttpClientFactory,并且还将在每个请求上重新运行以避免过期令牌,这使其对于Bearer Tokens、生成的客户端、池等非常有用。
太长不看:使用HttpClientFactory
和一个DelegatingHandler
来作为中间件处理所有传出请求与您配置的客户端。
这是我如何添加我的Azure Identity Bearer(由Azure进行管理),但当然您可以按照自己的方式获取令牌;
using Microsoft.Azure.Services.AppAuthentication;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class BearerTokenHandler : DelegatingHandler
{
public BearerTokenHandler(AzureServiceTokenProvider tokenProvider, string resource)
{
TokenProvider = tokenProvider;
Resource = resource;
}
public AzureServiceTokenProvider TokenProvider { get; }
public string Resource { get; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!request.Headers.Contains("Authorization"))
{
// Fetch your token here
string token = await TokenProvider.GetAccessTokenAsync(Resource);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
}
return await base.SendAsync(request, cancellationToken);
}
}
我在Startup中这样配置我的类型化客户端(由NSwag生成);
var accessTokenProvider = new AzureServiceTokenProvider("<your-connection-string-for-access-token-provider>");
builder.Services.AddHttpClient<IOrdersClient, OrdersClient>().ConfigureHttpClient(async conf =>
{
conf.BaseAddress = new Uri("<your-api-base-url>");
}).AddHttpMessageHandler(() => new BearerTokenHandler(accessTokenProvider, "https://your-azure-tenant.onmicrosoft.com/api"));
然后您可以在任何需要的地方注入您的 IOrdersClient,所有请求都将具有Bearer。
如果你想要重复使用 HttpClient
,建议不要使用 DefaultRequestHeaders
,因为它们会随着每个请求发送。
你可以尝试这样做:
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = new StringContent("...", Encoding.UTF8, "application/json"),
RequestUri = new Uri("...")
};
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes($"{user}:{password}")));
var response = await _httpClient.SendAsync(requestMessage);