如何在键入的HttpClient

时间:2019-12-12 10:50:25

标签: identityserver4 blazor blazor-server-side

我在服务器端Blazor应用程序中有一个IdentityServer4 / WebAPI设置和一个键入的HttpClient。我想在向API发出请求时动态添加访问令牌。但是HttpContextAuthenticationStateProvider都无法在AddHttpClient方法或AddHttpMessageHandler中访问。

这在本地可用,但在服务器httpContextAccessor上运行为空:

        services.AddHttpClient<IMyClient, MyClient>((serviceProvider, client) =>
        {       
            var httpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
            var accessToken = await httpContextAccessor.HttpContext.GetTokenAsync("access_token");
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); 
        }).AddHttpMessageHandler<MyApiBearerTokenHandler>();

尝试访问AuthenticationStateProvider

        services.AddHttpClient<IMyClient, MyClient>((serviceProvider, client) =>
        {       
            var authStateProvider = serviceProvider.GetService<AuthenticationStateProvider>();
        }).AddHttpMessageHandler<MyApiBearerTokenHandler>();

引发以下错误:

  

'无法解析范围服务   'Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider'   来自根提供商。”

如何将访问令牌放入AddHttpClient?我完全走错了路吗?

0 个答案:

没有答案