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!