Is setting the Authorization header in HttpClient safe?

后端 未结 2 1834
天命终不由人
天命终不由人 2021-01-16 10:06

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 heade

相关标签:
2条回答
  • 2021-01-16 10:23

    Will other users have a way to access this same token, given that there is only one instance of this HttpClient?

    Yes, that is why you need to be careful when setting the default headers.

    Would I need to add the header each time I'm making a request with the same HttpClient object?

    No, because you set the default header all requests created with that object will have the header.

    For things like a Bearer token it is better to not put in the default headers and instead put it in the request header by creating a new HttpRequestMessage object, setting the headers you need there, then using HttpClient.SendAsync( passing in the request message to send the headers along with your request.

    0 讨论(0)
  • 2021-01-16 10:27

    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.

    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.

    0 讨论(0)
提交回复
热议问题