简体   繁体   English

NetWorkCredentials 未显示在标题中

[英]NetWorkCredentials not showing up in headers

I have two projects: a Web API project and a client project.我有两个项目:一个 Web API 项目和一个客户项目。

In the client application, I configure my HttpClient like this.在客户端应用程序中,我像这样配置我的HttpClient

services.AddHttpClient<TrackAndTraceClient>()
    .ConfigureHttpClient(httpClient =>
    {
        httpClient.BaseAddress = new Uri(settings.BaseUrl);
        httpClient.Timeout = TimeSpan.FromMinutes(5);
    })
    .ConfigurePrimaryHttpMessageHandler(serviceProvider =>
    {
        return new HttpClientHandler()
        {
            Credentials = new NetworkCredential(settings.Username, settings.Password),
        };
    });

And then in my class that calls the API:然后在我的 class 中调用 API:

public TrackAndTraceClient(IHttpClientFactory httpClientFactory, IOptions<TrackAndTraceSettings> settings)
{
    HttpClient = httpClientFactory.CreateClient(nameof(TrackAndTraceClient));
    Settings = settings.Value;
}

My Web API site implements basic authentication using the techniques described in this article .我的 Web API 站点使用本文中描述的技术实现基本身份验证。 But my code throws an exception because no Authorization header is found.但是我的代码抛出异常,因为没有找到授权header。

public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {

        // ...

        if (!Request.Headers.TryGetValue("Authorization", out StringValues authHeaderValues))
            throw new Exception("Missing Authorization header");

        // ...
    }
}

I can only get this to work by adding the following code to my class that calls the API:我只能通过将以下代码添加到调用 API 的 class 中来使其工作:

HttpClient.DefaultRequestHeaders.Add("ContentType", "application/json");
byte[] credentialsData = Encoding.UTF8.GetBytes($"{Settings.Username}:{Settings.Password}");
string credentials = Convert.ToBase64String(credentialsData);
HttpClient.DefaultRequestHeaders.Add("Authorization", $"Basic {credentials}");

Can anyone tell me why this last block of code is needed?谁能告诉我为什么需要最后一段代码? Why doesn't setting the credentials with NetworkCredential appear to do anything?为什么使用NetworkCredential设置凭据似乎没有任何作用? And how can I change my Web API so that it works with credentials specified the original way?以及如何更改我的 Web API 以便它使用原始方式指定的凭据?

Note that I'm also calling a third-party API, and the client is configured exactly the same way as in my first block of code.请注意,我还调用了第三方 API,并且客户端的配置方式与我的第一个代码块中的方式完全相同。 So I know that can be made to work.所以我知道这可以发挥作用。

From our conversation in the comments section -从我们在评论部分的对话中——

The implementation of your BasicAuthenticationHandler lacks adding the WWW-Authenticate HTTP header (with value Basic ). BasicAuthenticationHandler的实现缺少添加WWW-Authenticate HTTP header (值为Basic )。

That is the header upon which the HttpClient reacts to include the Authorization HTTP header when it receives a 401 Unauthorized response.那就是 header , HttpClient在收到401 Unauthorized响应时会做出反应以包含Authorization HTTP header。

To resolve the issue, add the line below to the BasicAuthenticationHandler .要解决此问题,请将下面的行添加到BasicAuthenticationHandler

Response.Headers.Add("WWW-Authenticate", "Basic");

Now the NetworkCredentials will go into the Authorization HTTP header.现在NetworkCredentials将 go 转换为Authorization HTTP header。


In short without being complete about how this works;简而言之,它的工作原理并不完整;
when a HttpClient makes a request (without Authorization header), and receives a 401 Unauthorized in combination with a WWW-Authenticate , it will make a 2nd attempt with the configured credentials - if any - in the Authorization HTTP header.HttpClient发出请求(没有Authorization标头)并收到401 UnauthorizedWWW-Authenticate组合时,它将使用Authorization HTTP header 中配置的凭据(如果有)进行第二次尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM