[英]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.据我了解,HttpClient 旨在创建一次并重复使用。 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:我使用 IdentityServer3 作为 OIDC/OAuth 服务器,我查看的示例为每个请求创建一个 HttpClient 并使用扩展方法设置不记名令牌:
var client = new HttpClient();
client.SetBearerToken(token);
SetBearerToken simply sets the default authorization header on a HttpClient: SetBearerToken 只是在 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:我有一个调用 ASP.NET Web API 的 ASP.NET Web 应用程序,并且我已经配置了它们,以便在进行调用时客户端身份流向 API,即在配置 OpenId 连接身份验证时,我设置了:
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).但是,如果主题声明在令牌中传递,我现在不能重用 HttpClient (例如,一个请求可能会在它被另一个请求发送之前覆盖其授权标头)。
If I want to reuse a HttpClient should I be setting the token into a HttpRequestMessage?如果我想重用 HttpClient,我应该将令牌设置为 HttpRequestMessage 吗? If not what is the recommended pattern for handling this scenario?如果不是,处理这种情况的推荐模式是什么?
You will definitely want to create your own HttpRequestMessage and use SendAsync .您肯定希望创建自己的HttpRequestMessage并使用SendAsync 。 Unfortunately, you will not have the extension method for setting the bearer token, but it is the best way to handle the HttpClient.不幸的是,您将没有设置承载令牌的扩展方法,但它是处理 HttpClient 的最佳方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.