C# 向标头添加授权

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19039450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:57:43  来源:igfitidea点击:

Adding authorization to the headers

c#windows-phone-8async-awaitdotnet-httpclient

提问by Jimmyt1988

I have the following code:

我有以下代码:

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

The response = await part just continues an ongoing loop and nothing happens. Any ideas what I am doing wrong?

response = await 部分只是继续一个持续的循环,什么也没有发生。任何想法我做错了什么?

The question really is, how do I send the following header:

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

Authorization: OAuth2 ACCESS_TOKEN

to an external web api

到外部 web api

采纳答案by Alaa Masoud

This line

这条线

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

Will produce this header value

将产生这个标题值

Authorization: ACCESS_TOKEN

Where ACCESS_TOKENis the value of authValue.Parameter. You want to assign the value you passed instead to get the required header

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

client.DefaultRequestHeaders.Authorization = authValue;

Will produce

会产生

Authorization: OAuth2 ACCESS_TOKEN

回答by John

I struggled with this. I kept getting an error saying "invalid format" because I have a custom implementation and the Authorization header is validated against certain standards. Adding the header this way however worked:

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

var http = new HttpClient();
http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=XXX");

回答by Yogurt The Wise

Had a similar issue when getting AuthenticationHeaderValue to work with my requests. I was also using JWT JsonWebToken from GitHub. I was able to get a token from the API, but was struggling to use it in other GETs and POSTs.

在让 AuthenticationHeaderValue 处理我的请求时遇到了类似的问题。我还使用了来自 GitHub 的 JWT JsonWebToken。我能够从 API 获取令牌,但在其他 GET 和 POST 中难以使用它。

var jwt = JsonWebToken.Encode(token, APISECRET, JwtHashAlgorithm.HS256);
var tk = GetTokenFromApi(); // basically returns an encrypted string.

Manually using WebRequest: Which worked fine.

手动使用 WebRequest:效果很好。

request.ContentType = "application/json";
request.Method = "POST";
request.Headers.Set("Authorization", string.Format("Bearer {0}", tk));

When we switched to an HttpClient, and used the AuthenticationHeaderValue, could not figure out how to set it up correctly.After looking at the request string, i saw it added the "Authorization" for me. Played around with parameters, and this finally this worked.

当我们切换到一个HttpClient,并使用AuthenticationHeaderValue 时,无法弄清楚如何正确设置它。查看请求字符串后,我看到它为我添加了“授权”。玩弄参数,这终于奏效了。

 var authenticationHeaderValue = new AuthenticationHeaderValue("Bearer", tk);

回答by Nico

Maybe intresting for other people. Since I searched on this for a long time. But you have to save your cookies also and give it with your next request. First this is how i got my authentication code and hold my cookies in a static variable (in the first time i call this method I give an empty value to 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);
            }
        }

    }

After this if I do any request to the api I include the cookies (token is what you get from the first response as a result) public static async Task Get(string path, string token = "") {

在此之后,如果我对 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);
        }
    }