I would like to migrate my hosted WASM project to a Blazor Web App.
In my project, the server authenticates the user using OpenID connect by communicating to KeyCloak. The client receives the JWT bearer token from the server and uses it to communicate to another hosted API. The implementation of the authorization is at the moment quite customised.
I used the example https://github.com/dotnet/blazor-samples/tree/main/9.0/BlazorWebAppOidc (and not the BFF example, because I want the client to directly communicate to the external API) in order to get an idea of how to implement the authorization for a Blazor WebApp. This example uses a PersistingAuthenticationStateProvider
and CookieOidcRefresher
.
I altered the example so it's configured correctly to work with KeyCloak. It works with server-side rendering and client-side rendering. I also get the server-side to communicate to the external API using the bearer token, by registering a ServerTokenHandler
and adding it to the HttpClient
using:
public class ServerTokenHandler(IHttpContextAccessor httpContextAccessor) : DelegatingHandler{ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var httpContext = httpContextAccessor.HttpContext; if (httpContext == null) throw new InvalidOperationException("HttpContext must not be null"); // Retrieve the access token from the current user's claims var accessToken = await httpContext.GetTokenAsync("access_token"); if (!String.IsNullOrEmpty(accessToken)) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); return await base.SendAsync(request, cancellationToken); }}
But how can I get the client to add the bearer token to the headers on a HttpClient
?I created a custom authorization message handler and added it to the HttpClient
:
public class CustomAuthorizationMessageHandler : BaseAddressAuthorizationMessageHandler{ public CustomAuthorizationMessageHandler(IAccessTokenProvider provider, NavigationManager navigation) : base(provider, navigation) { this.ConfigureHandler( authorizedUrls: ["https://api.nl"], scopes: ["openid", "email", "profile"]); }}
But now I have to implement the IAccessTokenProvider
myself and I am stuck from there...
Can someone help me out?
Thanks in advance!