在HttpClient中设置授权标头是否安全? [英] Is setting the Authorization header in HttpClient safe?

查看:75
本文介绍了在HttpClient中设置授权标头是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在MVC5 ASP.NET项目中工作,并了解到要从控制器向WEB API发送经过身份验证的请求,我可以执行以下操作向标头添加令牌(使用示例代码):

I'm working in a MVC5 ASP.NET project, and learned that to send authenticated requests to a WEB API from the controller I could do the following to add a token to the header(using an example code):

public static class APICaller
{
    // Use a single instance for HttpClient to reduce overhead
    private static readonly HttpClient client = new HttpClient();

    //Set the Authorization Header
    public static string SetHeader( string token )
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        return("Success");
    }
}

是否在HttpClient线程安全的情况下以这种方式设置标头?假设此HttpClient只有一个实例,其他用户是否可以使用一种方法来访问同一令牌?

Is setting the header this way on the HttpClient thread-safe? Will other users have a way to access this same token, given that there is only one instance of this HttpClient?

我想再问一个问题,以更好地了解它的工作原理.每次使用相同的HttpClient对象发出请求时,都需要添加标头吗?

I'd like to ask one more question to get a better understanding of how it works. Would I need to add the header each time I'm making a request with the same HttpClient object?

推荐答案

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

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.

这篇关于在HttpClient中设置授权标头是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆