Why is the bearer token not sent in blazor webassembly?

Viewed 314

I'm trying to configure my http client to send the jwt token

using this code

public class HttpClientWithToken
    {
        public HttpClientWithToken(HttpClient httpClient)
        {
            HttpClient = httpClient;
        }

        public HttpClient HttpClient { get; }
    }

public static async Task Main(string[] args)
            {
                var builder = WebAssemblyHostBuilder.CreateDefault(args);
                builder.RootComponents.Add<App>("#app");
    
                builder.Services.AddHttpClient<HttpClientWithToken>(
                     client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
                     .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
    
                ConfigureServices(builder.Services);
    
                var host = builder.Build();

                await host.RunAsync();
            }

I get the error : " no service for type 'microsoft.aspnetcore.components.webassembly.authentication.baseaddressauthorizationmessagehandler' has been registered"

Using this code

public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("#app");

            builder.Services.AddSingleton<BaseAddressAuthorizationMessageHandler>();

            builder.Services.AddHttpClient<HttpClientWithToken>(
                 client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
                 .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

            ConfigureServices(builder.Services);

            var host = builder.Build();

            await host.RunAsync();
        }

I get the error : "Unable to resolve service for type 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider' while attempting to activate 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler'."

What am I missing? Based on the exemple I'm following the first code should send the bearer in the headers.

I can call my api and I get the bearer token when setting the HttpClient.DefaultRequestHeaders.Authorization, but I can't get the token using the configuration.

0 Answers
Related