My Blazor .NET 8 WASM app uses the StrawberryShake GraphQL client to connect to a HotChocolate GraphQL endpoint in an ASP NET Web API project. I am following the official docs but I'm having trouble injecting the access token into the request.
Here's what I have tried: AddGqlClient()
is a method generated by StrawberryShake:
builder.Services.AddMsalAuthentication(...);
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddAuthorizationCore(...);
builder.Services.AddGqlClient()
.ConfigureHttpClient(async (sp, client) =>
{
var provider = sp.GetRequiredService<Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider>();
var tokenResult = await provider.RequestAccessToken();
tokenResult.TryGetToken(out AccessToken? jwt);
client.BaseAddress = new Uri($"{apiUrl}/graphql");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt.Value);
});
The builds okay, but when I make a request, I get an error
System.InvalidOperationException: Cannot resolve scoped service 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider' from root provider
Can someone share some insights on what I can improve? Thank you in advance for any help!
As so often, after asking here the solution was found. Posting here so it might be helpful for someone. The key was to use the factory approach as outlined here.
builder.Services.AddHttpClient(GqlClient.ClientName, client => client.BaseAddress = new Uri($"{apiUrl}/graphql"))
.AddHttpMessageHandler<ApiAuthzRequestMessageHandler>();
builder.Services.AddGqlClient();
The httpclient name GqlClient.ClientName
was also generated by StrawberryShake so there is a match.