Is setting the Authorization header in HttpClient safe?

后端 未结 2 1833
天命终不由人
天命终不由人 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: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.

提交回复
热议问题