简体   繁体   中英

How to set OIDC/OAuth bearer token in C# HttpClient when flowing client subject

As I understand it HttpClient has been designed to be created once and reused. I am using IdentityServer3 as an OIDC/OAuth server and the samples I have looked at create a HttpClient per request and set the bearer token using an extension method:

var client = new HttpClient();
client.SetBearerToken(token);

SetBearerToken simply sets the default authorization header on a HttpClient:

client.DefaultRequestHeaders.Authorization = 
                new AuthenticationHeaderValue("Bearer", token);

I have a ASP.NET web application calling a ASP.NET Web API and I have configured them so that client identity flows to the API when a call is made, ie when configuring OpenId connect authentication I set:

OpenIdConnectAuthenticationOptions.ResponseType = "id_token token"

However, if the subject claim is passed in the token I can't now reuse the HttpClient (a request could have its authorization header overwritten before it is sent by another request for example).

If I want to reuse a HttpClient should I be setting the token into a HttpRequestMessage? If not what is the recommended pattern for handling this scenario?

You will definitely want to create your own HttpRequestMessage and use SendAsync . Unfortunately, you will not have the extension method for setting the bearer token, but it is the best way to handle the HttpClient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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