且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在HttpClient中设置授权标头是否安全?

更新时间:2023-01-09 23:12:42

使用这种方法,一旦在静态实例上设置了默认请求标头,它将保持设置状态,而无需继续设置它.这意味着,如果有多个请求进入服务器,则可能会遇到这样的情况:为一个用户设置标头,然后在另一个请求发出请求之前,由另一个请求更改标头.

With the approach you have, once you've set the default request header on your static instance, it will remain set without you having to keep setting it. This means that if you have multiple requests coming into your server, you could end up in a situation where the header is set for one user and then changed by another request before that first request makes it out the door.

避免这种情况的一种选择是使用使用特定于用户的授权标头时 SendAsync .这样,您就可以将标头绑定到特定的消息,而不是将其设置为 HttpClient 本身的默认值.

One option to avoid this would be to use SendAsync when using user-specific authorisation headers. This allows you to tie the header to a specific message, rather than setting it as a default for the HttpClient itself.

代码有点冗长,但是看起来像这样:

The code is a bit more verbose, but would look something like this:

using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://path/to/wherever"))
{
    httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "TheToken");

    using (var httpResponseMessage = httpClient.SendAsync(httpRequestMessage))
    {
        // ...
    }
}

如您所见,标头是在每个请求上专门设置的,因此混淆了标头的问题消失了.明显的缺点是这种语法更冗长.

As you can see, the header is set specially on each request and therefore the issue of mixing up the headers goes away. The obvious downside is that this syntax is more verbose.