0

我正在尝试使用我的 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();
     }
}

上面的代码是否设置了任何令牌,我在这里缺少什么?在授权标头中放置承载令牌的位置。

谢谢!

4

1 回答 1

2

为了与来自 httpclient 的任何请求一起发送令牌,您需要在之前注入它,并且您需要使用AddClientAccessTokenClient下面的方法AddAccessTokenManagement

services.AddClientAccessTokenClient("client", configureClient: client =>
{
    client.BaseAddress = new Uri("http://localhost:10811/");
});

并且您需要指定要使用的配置名称才能创建httpclient

_client = factory.CreateClient("client");

现在你可以简单地打电话

var response = await HttpClient.GetAsync("test"); //no need to specify the full URL
于 2020-05-14T14:41:35.763 回答