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?