[英]How to add bearer token authentication to typed HttpClient in Asp.Net Core 6
I'm trying to setup a web api using ASP.Net Core 6 so that users can hit my end points and then I do some work in D365 behind the scenes using a privileged account.我正在尝试使用 ASP.Net Core 6 设置 web api,以便用户可以达到我的终点,然后我使用特权帐户在幕后的 D365 中做一些工作。 I'm using a typed HTTP Client, but I'm not sure how to plugin the bearer authentication so that all the requests from this client have the correct Authorization header attached.
我正在使用类型化的 HTTP 客户端,但我不确定如何插入承载身份验证,以便来自该客户端的所有请求都附加了正确的授权 header。
Program.cs程序.cs
builder.Services.AddHttpClient<D365Service>();
D365Service.cs D365Service.cs
private readonly HttpClient httpClient;
public D365Service(HttpClient httpClient)
{
this.httpClient = httpClient;
this.httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
this.httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
// a whole bunch of other headers
// Is this where I can add in the bearer Authorization header? How do I generate that token?
}
Any help is appreciated.任何帮助表示赞赏。 Thanks.
谢谢。
To add the token to your httpcl.net将令牌添加到您的 httpcl.net
you should use the following code你应该使用下面的代码
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue($"Bearer",$"{accessToken}");
How do I generate that token
我如何生成该令牌
as @DiplomacyNotWar explained in his comment you should be able to generate that token by following the instructions of the service you are connecting to正如@DiplomacyNotWar 在他的评论中解释的那样,您应该能够按照您要连接的服务的说明生成该令牌
Some services will share user name and password ( app Id & secret Key ) and you could use this to set your basic Authentication then you will be able to call your token end point that return the access token that you will be able to use it with your httpcl.net一些服务将共享用户名和密码(应用程序 ID 和密钥),您可以使用它来设置您的基本身份验证,然后您将能够调用您的令牌端点,返回您将能够使用它的访问令牌你的 httpcl.net
Regards,问候,
I know 2 ways to add token to HttpClient.我知道两种向 HttpClient 添加令牌的方法。 But I don't know what's the difference between them
但我不知道它们之间有什么区别
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + #YourToken);
And和
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", #YourToken);
they work well.他们工作得很好。 but I think they will have something different.
但我认为他们会有不同的东西。 if you know, please show me
如果你知道,请告诉我
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.