Musaffar Patel
Musaffar Patel

Reputation: 1372

Adding JWT Bearer token to all requests in Blazor Client app

I am currently experimenting in creating a client side Blazor web SPA. The app connects to an external API through which I can currently successfully authenticate the user with and as a result the external API responds with a JWT Token.

Now the nest step is to ensure the JWT token is attached to the headers of all requests made by the client app (with exception of some pages or requests).

So far, I have accomplished this creating a custom Http service with methods for Get and Post. These methods attach the JWT token available locally.

However, with other client frameworks such as Angular and Svelte, I was able to intercept normal http requests and add headers if necessary and also handle responses accordingly without the need for a custom HttpService.

Is this possible with Blazor? I've spent quite a few hours going through tutorials online but they all seem to involve additional features such as server side authentication and roles etc. I just need an example of a simple middleware class to intercept requests placed through System.Net.Http.HttpClient.

This is only my second day with Blazor therefore some code examples would be very helpful.

Upvotes: 3

Views: 4397

Answers (2)

Christian Gollhardt
Christian Gollhardt

Reputation: 17034

Create and inject a custom IAccessTokenProvider when you want to bypass the default provider:

public interface IAccessTokenProvider
{
    /// <summary>
    /// Tries to get an access token for the current user with the default set of permissions.
    /// </summary>
    /// <returns>A <see cref="ValueTask{AccessTokenResult}"/> that will contain the <see cref="AccessTokenResult"/> when completed.</returns>
    ValueTask<AccessTokenResult> RequestAccessToken();

    /// <summary>
    /// Tries to get an access token with the options specified in <see cref="AccessTokenRequestOptions"/>.
    /// </summary>
    /// <param name="options">The <see cref="AccessTokenRequestOptions"/> for provisioning the access token.</param>
    /// <returns>A <see cref="ValueTask{AccessTokenResult}"/> that will contain the <see cref="AccessTokenResult"/> when completed.</returns>
    ValueTask<AccessTokenResult> RequestAccessToken(AccessTokenRequestOptions options);
}

Then configure your client this way:

builder.Services.AddHttpClient("ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
    .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

Or you create and inject your own AuthorizationMessageHandler. Here is the source code, to get some inspiration.

Upvotes: 2

fuzzybear
fuzzybear

Reputation: 2405

Normally in your auth service once a user is authenticated. Add a header using HttpClient.DefaultRequestHeader will add the bearer token to all requests

HttpClient.DefaultRequestHeaders Property

_client.DefaultRequestHeaders.Add("Authorization", $"Bearer {user.AccessToken}");

Remove

_client.DefaultRequestHeaders.Remove("Authorization");

Add HTTP client service in Program.cs

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

Upvotes: 1

Related Questions