I have spent quite a lot of time trying to get authentication with bearer token to work from my localhost development to an Azure Function API requiring a bearer token in the authorization header.
In the guide found here the token should be attached automatically to any client with the base address I configured for my Function App API, if I read the documentation correct.
I have this in my program.cs:
builder.Services.AddHttpClient("ServerAPI",
client => client.BaseAddress = new Uri("https://myapp.azurewebsites.net"))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("ServerAPI"));
And I use the Azure AD the Function App lives in for authentication:
builder.Services.AddMsalAuthentication(options =>
{
options.ProviderOptions.DefaultAccessTokenScopes.Add("https://graph.microsoft.com/User.Read");
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
});
My Index.razorpage has @attribute [Authorize] and gets authenticated correctly. A token is granted and saved in both Session Storage and Local Storage according to developer tools in Edge.
The issue is, that the bearer token is not added to the client I use in my code in the index.razor file. I have this code:
private async Task GetMyData()
{
var client = HttpClientFactory.CreateClient("ServerAPI");
profile = await client.GetFromJsonAsync<UserProfile[]>("api/GetMyData");
}
but when I press this button:
<button class="btn btn-primary" @onclick="GetMyData">Get Data</button>
the call is executed as expected, but the bearer token is not added to the header and thus the execution fails.
I would expect to se authorization: bearer ey34h7two4ntw3yt4m... somewhere here:

I have tried all variations in the guide mentioned initially, but I have not had success getting the bearer token attached to the call with any of them.
What am I missing?
In the end, re-reading this post: Automatically Attaching Access Token to HTTP Client in Blazor wasm the 5th time fixed my issue.
I had to add the CustomAuthorizationMessageHandler to my client.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With