0

I've got a IdentityServer4/WebAPI setup and a typed HttpClient in my server-side Blazor application. I want to add the access token dynamically when a request to the API is made. But neither the HttpContext nor the AuthenticationStateProvider is accessible in the AddHttpClient method or in the AddHttpMessageHandler.

This works locally but running on the server httpContextAccessor is null:

        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>();

Trying to access the AuthenticationStateProvider

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

throws the following error:

'Cannot resolve scoped service 'Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider' from root provider.'

How do I get the access token into AddHttpClient? Am I completely on the wrong track?

Pascal R.
  • 2,024
  • 1
  • 21
  • 35
  • Does this answer your question? [Configure HttpClientFactory to use data from the current request context](https://stackoverflow.com/questions/51358870/configure-httpclientfactory-to-use-data-from-the-current-request-context) –  Dec 16 '19 at 10:42
  • No it doesn't but thanks anyway. I have seen that thread already and it helped me understand the topic but it does not seem to work for Blazor. – Pascal R. Dec 23 '19 at 11:14

0 Answers0