在使用IdentityModel.AspNetCore -1.0.0-rc.4.1时,得到401个unauthorize。

问题描述 投票:0回答:1

我试图在我的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();
     }
}

以上代码是否设置了任何标记,我缺少什么?在授权头中的Bearer token应该放在哪里。

谢谢

c# asp.net-core identitymodel
1个回答
1
投票

为了在https客户端的任何请求中发送令牌,你需要在之前注入令牌,并且你需要使用 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
© www.soinside.com 2019 - 2024. All rights reserved.