向标头添加授权
本文关键字:授权 添加 | 更新日期: 2023-09-27 18:33:08
我有以下代码:
...
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
我为此苦苦挣扎。我一直收到一条错误消息,说"格式无效",因为我有一个自定义实现,并且授权标头已根据某些标准进行验证。但是,以这种方式添加标头是有效的:
var http = new HttpClient();
http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=XXX");
此行
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(authValue.Parameter);
将生成此标头值
Authorization: ACCESS_TOKEN
其中ACCESS_TOKEN
是authValue.Parameter
的值。您希望分配传递的值以获取所需的标头
client.DefaultRequestHeaders.Authorization = authValue;
将产生
Authorization: OAuth2 ACCESS_TOKEN
在让 AuthenticationHeaderValue 处理我的请求时遇到了类似的问题。我还使用了GitHub上的JWT JsonWebToken。我能够从 API 获得令牌,但很难在其他 GAT 和 POST 中使用它。
var jwt = JsonWebToken.Encode(token, APISECRET, JwtHashAlgorithm.HS256);
var tk = GetTokenFromApi(); // basically returns an encrypted string.
手动使用网络请求:哪个工作正常。
request.ContentType = "application/json";
request.Method = "POST";
request.Headers.Set("Authorization", string.Format("Bearer {0}", tk));
当我们切换到 HttpClient 并使用 AuthenticationHeaderValue 时,无法弄清楚如何正确设置它。查看请求字符串后,我看到它为我添加了"授权"。玩弄了参数,这终于奏效了。
var authenticationHeaderValue = new AuthenticationHeaderValue("Bearer", tk);
在代码中,您正在执行以下操作:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{token}");
我认为以下内容应该以相同的方式工作,而无需使用字符串插值:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
这是因为字符串插值只是生成一个包含令牌的字符串!
也许是为了其他人而感到不安。因为我搜索了很长时间。但是您还必须保存您的 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(令牌是您从第一个响应中获得的结果) 公共静态异步任务获取(字符串路径,字符串令牌 = ") {
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);
}
}