'Blazor authentication with OpenId: call HttpClient with JWT token

In my Blazor Web Assembly project with .NET6, I have the authentication with Identity Server (OpenId). In the Program.cs I read the configuration from the app.settings with

builder.Services.AddOidcAuthentication(options =>
{
    builder.Configuration.Bind("oidc", options.ProviderOptions);
    options.UserOptions.RoleClaim = "role";
})
.AddAccountClaimsPrincipalFactory<MultipleRoleClaimsPrincipalFactory<RemoteUserAccount>>();

Also, I use HttpClient to call an API and retrieve data.

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(apiEndpoint) });

Now, the point is that I want to use the user token to call the API. I tried different functions like AuthenticationService but there is not a method to read the token. I tried to use AuthenticationStateProvider but again nothing.

I saw this post on Stackoverflow but it is not my case because I have a WebAssembly.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source