我有一个HttpClient,我正在使用一个REST API。但是,我在设置授权标头时遇到了麻烦。我需要将标头设置为我从执行OAuth请求中接收到的令牌。 我看到了一些。net的代码,建议如下:

httpClient.DefaultRequestHeaders.Authorization = new Credential(OAuth.token);

然而,凭据类在WinRT中不存在。有人知道如何设置授权头吗?


当前回答

Firstly, I wouldn't use HttpClient directly. It's too easy to make mistakes - particularly in the area of headers. The DefaultHeadersCollection is not immutable and not thread-safe because other parts of the app can change the headers on you. It's best to set the headers when you make the call. If you are working with an abstraction, and that is recommended because the classes in this area are a bit of a mess, you would want to have a headers collection and put those on your HttpRequestMessage before you send it. You need to make sure you put the content headers on the content, and not the message.

代码引用

foreach (var headerName in request.Headers.Names)
{
    //"Content-Type"
    if (string.Compare(headerName, HeadersExtensions.ContentTypeHeaderName, StringComparison.OrdinalIgnoreCase) == 0)
    {
        //Note: not sure why this is necessary...
        //The HttpClient class seems to differentiate between content headers and request message headers, but this distinction doesn't exist in the real world...
        //TODO: Other Content headers
        httpContent?.Headers.Add(HeadersExtensions.ContentTypeHeaderName, request.Headers[headerName]);
    }
    else
    {
        httpRequestMessage.Headers.Add(headerName, request.Headers[headerName]);
    }
}

下面是一个数据结构,您可以使用它来发送包含头部的请求。

代码引用

public interface IRequest
{
    CancellationToken CancellationToken { get; }
    string? CustomHttpRequestMethod { get; }
    IHeadersCollection Headers { get; }
    HttpRequestMethod HttpRequestMethod { get; }
    AbsoluteUrl Uri { get; }
}

public interface IRequest<TBody> : IRequest
{
    TBody? BodyData { get; }
}

和,一个头文件集合:

代码引用

public sealed class HeadersCollection : IHeadersCollection
{
    #region Fields
    private readonly IDictionary<string, IEnumerable<string>> dictionary;
    #endregion

    #region Public Constructors

    public HeadersCollection(IDictionary<string, IEnumerable<string>> dictionary) => this.dictionary = dictionary;

    public HeadersCollection(string key, string value) : this(ImmutableDictionary.CreateRange(
                new List<KeyValuePair<string, IEnumerable<string>>>
                {
                    new(key, ImmutableList.Create(value))
                }
                ))
    {
    }

    #endregion Public Constructors

    #region Public Properties
    public static HeadersCollection Empty { get; } = new HeadersCollection(ImmutableDictionary.Create<string, IEnumerable<string>>());
    public IEnumerable<string> Names => dictionary.Keys;
    IEnumerable<string> IHeadersCollection.this[string name] => dictionary[name];
    #endregion Public Properties

    #region Public Methods
    public bool Contains(string name) => dictionary.ContainsKey(name);

    public IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumerator() => dictionary.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => dictionary.GetEnumerator();
    public override string ToString() => string.Join("\r\n", dictionary.Select(kvp => $"{kvp.Key}: {string.Join(", ", kvp.Value)}\r\n"));
    #endregion
}

在这里查看所有工作代码和示例。

其他回答

使用现有的库可能更容易。

例如,Identity Server 4中添加了下面的扩展方法 https://www.nuget.org/packages/IdentityModel/

 public static void SetBasicAuthentication(this HttpClient client, string userName, string password);
    //
    // Summary:
    //     Sets a basic authentication header.
    //
    // Parameters:
    //   request:
    //     The HTTP request message.
    //
    //   userName:
    //     Name of the user.
    //
    //   password:
    //     The password.
    public static void SetBasicAuthentication(this HttpRequestMessage request, string userName, string password);
    //
    // Summary:
    //     Sets a basic authentication header for RFC6749 client authentication.
    //
    // Parameters:
    //   client:
    //     The client.
    //
    //   userName:
    //     Name of the user.
    //
    //   password:
    //     The password.
    public static void SetBasicAuthenticationOAuth(this HttpClient client, string userName, string password);
    //
    // Summary:
    //     Sets a basic authentication header for RFC6749 client authentication.
    //
    // Parameters:
    //   request:
    //     The HTTP request message.
    //
    //   userName:
    //     Name of the user.
    //
    //   password:
    //     The password.
    public static void SetBasicAuthenticationOAuth(this HttpRequestMessage request, string userName, string password);
    //
    // Summary:
    //     Sets an authorization header with a bearer token.
    //
    // Parameters:
    //   client:
    //     The client.
    //
    //   token:
    //     The token.
    public static void SetBearerToken(this HttpClient client, string token);
    //
    // Summary:
    //     Sets an authorization header with a bearer token.
    //
    // Parameters:
    //   request:
    //     The HTTP request message.
    //
    //   token:
    //     The token.
    public static void SetBearerToken(this HttpRequestMessage request, string token);
    //
    // Summary:
    //     Sets an authorization header with a given scheme and value.
    //
    // Parameters:
    //   client:
    //     The client.
    //
    //   scheme:
    //     The scheme.
    //
    //   token:
    //     The token.
    public static void SetToken(this HttpClient client, string scheme, string token);
    //
    // Summary:
    //     Sets an authorization header with a given scheme and value.
    //
    // Parameters:
    //   request:
    //     The HTTP request message.
    //
    //   scheme:
    //     The scheme.
    //
    //   token:
    //     The token.
    public static void SetToken(this HttpRequestMessage request, string scheme, string token);

对于现在(2021年)找到这个旧线程的人,请看看这个关于HttpClientFactory的文档,它是可注入的,也会在每个请求上重新运行,避免过期的令牌,这将使它对承载令牌,生成的客户端,池等有用。

TL;DR:使用HttpClientFactory和一个DelegatingHandler,它将作为与您配置的客户端的所有外发请求的中间件。

这就是我如何为Azure身份添加我的承载者(由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,所有的请求都会有承载者。

使用System.Net.Http程序集的AuthenticationHeaderValue类

public AuthenticationHeaderValue(
    string scheme,
    string parameter
)

我们可以像这样设置或更新httpclient现有的授权头:

httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TokenResponse.AccessToken);

我建议你:

HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");

然后你可以这样使用它:

var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
    responseMessage = await response.Content.ReadAsAsync<ResponseMessage>();
}

使用基本授权和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();
}