我正在尝试使用我的 asp.net core 3.1 应用程序中的客户端凭据流访问受保护的 api 之一。
对于我正在使用的令牌管理IdentityModel.AspNetCore -1.0.0-rc.4.1
。
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient<ApiService>(client =>
{
client.BaseAddress = new Uri("http://localhost:10811/");
})
.AddClientAccessTokenHandler();
services.AddAccessTokenManagement(options =>
{
options.Client.Clients.Add("auth", new ClientCredentialsTokenRequest
{
Address = "http://localhost:10811/token",
ClientId = "client1",
ClientSecret = "Supersecret"
});
});
在尝试访问受保护的 api 服务时,我总是收到 401。
ApiService 代码,
public class ApiService
{
public HttpClient HttpClient;
public ApiService(HttpClient client)
{
HttpClient = client;
}
public async Task<string> GetContactsAsync()
{
var response = await HttpClient.GetAsync("http://localhost:10811/test");
response.EnsureSuccessStatusCode();
return "Done";
}
}
我在这里打电话
public class MyCallService
{
private readonly IHttpClientFactory _clientFactory;
public MyCallService(IHttpClientFactory clientFactory)
{
if (clientFactory != null) _clientFactory = clientFactory;
}
Public void Call()
{
var client = _clientFactory.CreateClient();
var apiService= new ApiService(client);
await apiService.GetContactsAsync();
}
}
上面的代码是否设置了任何令牌,我在这里缺少什么?在授权标头中放置承载令牌的位置。
谢谢!