Integrating OpenID Authentication in Blazor WebApp for External API Access with JWT

I’m looking to transition my hosted WebAssembly application to a Blazor Web App. Currently, the server utilizes OpenID Connect for user authentication with KeyCloak, and it provides a JWT bearer token that the client employs to interact with another external API. The current authorization setup is quite personalized.

I referenced a specific project on GitHub (not the BFF approach) for guidance on integrating authorization in a Blazor Web App. This project utilizes a SessionAuthenticationStateProvider and TokenRefresher.

I have modified the example to ensure compatibility with KeyCloak, and it works seamlessly with both server-side and client-side rendering. Additionally, I set up server communication with the external API using the bearer token by implementing a AuthTokenHandler like this:

public class AuthTokenHandler(IHttpContextAccessor contextAccessor) : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
    {
        var context = contextAccessor.HttpContext;

        if (context == null)
            throw new InvalidOperationException("HttpContext cannot be null");

        var token = await context.GetTokenAsync("access_token");

        if (!string.IsNullOrWhiteSpace(token))
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

        return await base.SendAsync(request, ct);
    }
}

Now, I’m trying to figure out how to append the bearer token to the headers for a HttpClient on the client side. I devised a custom message handler and attached it to the HttpClient:

public class MyAuthorizationHandler : BaseAddressAuthorizationHandler
{
    public MyAuthorizationHandler(IAccessTokenProvider tokenProvider, NavigationManager navManager)
        : base(tokenProvider, navManager)
    {
        this.ConfigureHandler(
            authorizedUris: ["https://api.nl"],
            requiredScopes: ["openid", "email", "profile"]);
    }
}

However, I now need to implement the IAccessTokenProvider, and I’m unsure how to proceed. Any advice would be greatly appreciated! Thank you!

Hey Bob_Clever,

To implement IAccessTokenProvider in your Blazor Web App, ensure that your authentication library (e.g., Microsoft.Authentication.WebAssembly.Msal) has been configured correctly. Usually, you’ll inject the token provider in your service collection. Here's a simple example:

services.AddHttpClient("YourClient", client => client.BaseAddress = new Uri("https://api.nl")). AddHttpMessageHandler();

services.AddScoped<IAccessTokenProvider, Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessTokenProvider>();

Make sure your MyAuthorizationHandler is registered and used with your HttpClient to add the Bearer token as needed.

Cheers!