26

我有以下代码:

...
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;
}

response = await 部分只是继续一个正在进行的循环,没有任何反应。任何想法我做错了什么?

真正的问题是,我如何发送以下标头:

Authorization: OAuth2 ACCESS_TOKEN

到外部 web api

4

5 回答 5

68

我为此苦苦挣扎。我一直收到一条错误消息,说“格式无效”,因为我有一个自定义实现,并且 Authorization 标头已根据某些标准进行了验证。但是以这种方式添加标题是有效的:

var http = new HttpClient();
http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=XXX");
于 2014-07-04T13:43:08.473 回答
28

这条线

client.DefaultRequestHeaders.Authorization = 
           new AuthenticationHeaderValue(authValue.Parameter);

将产生此标头值

Authorization: ACCESS_TOKEN

ACCESS_TOKEN的值在哪里authValue.Parameter。您想分配您传递的值而不是获取所需的标头

client.DefaultRequestHeaders.Authorization = authValue;

会产生

Authorization: OAuth2 ACCESS_TOKEN
于 2013-09-26T22:45:52.910 回答
12

在让 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);
于 2017-12-20T19:57:42.207 回答
2

也许对其他人很感兴趣。因为我在这方面搜索了很长时间。但是您还必须保存您的 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);
        }
    }
于 2019-03-24T21:35:44.413 回答
1

在您的代码中,您正在执行以下操作:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{token}");

我认为以下应该以相同的方式工作而不使用字符串插值:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

这是因为字符串插值只是生成一个带有标记的字符串!

于 2020-09-08T17:14:41.190 回答