Can't get AuthorizationMessageHandler in Blazor WebAssembly to work due to service lifetime issues

Viewed 727

I cannot get an HttpClient with AuthorizationMessageHandler working.

I have a project set up using the Microsoft.AspNetCore.Components.WebAssembly.Authentication package, and wired up for OIDC. That's working fine. Now, I want to make an http call to an API in another domain, using the access token provided during the OIDC authentication.

Based on https://docs.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/additional-scenarios?view=aspnetcore-5.0#typed-httpclient, this should be a simple task, but I'm having all sorts of problems with the service collection. Here's what I have to set up a typed HttpClient:

builder.Services.AddScoped<AuthorizationMessageHandler>();

builder.Services.AddHttpClient<IAuthorizationClient, AuthorizationClient>(client => client.BaseAddress = new Uri(authUrl))
   .AddHttpMessageHandler(sp => sp.GetRequiredService<AuthorizationMessageHandler>().ConfigureHandler(new[] { authUrl }));

The issue here, for example, is that AuthorizationMessageHandler requires an IAccessTokenProvider in the constructor, which Blazor provides as a Scoped service. However, the HttpClientFactory is registered as a singleton service. When the HttpClientFactory tries to activate an instance of AuthorizationMessageHandler, it fails with the following error:

Cannot resolve scoped service 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler' from root provider.

Registering AuthorizationMessageHandler as a Singleton, I get:

Cannot consume scoped service 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider' from singleton 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler'.

Registering AuthorizationMessageHandler as a Transient, I get:

Cannot resolve 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler' from root provider because it requires scoped service 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider'.

I'm out of ideas on how to get this to work. All the examples in the referenced link above don't appear to work.

I've tried this with both net5.0 and net6.0, with the same result.

0 Answers
Related