Pass Access Token to API

I have a Blazor server app and I have successfully retrieved the access token for my custom API (not the Auth0 API) and saved that token in localStorage. I have created the HttpClient in the Program.cs of the Blazor app but I am unsure how to pass the token I have stored on each request of my API. I have a client class that injects the HttpClient but I guess I’m unsure how to attach the token in my razor page when I need to make a request.

I saw something about adding a Messagehandler when I add the HttpClient to the services in Program.cs but I don’t understand how the token gets added later.

Here is what I have so far. In my Program.cs:

// Configure httpClient for API
builder.Services.AddHttpClient<BowlTournamentsClient>(client =>
{
    client.BaseAddress = new Uri(builder.Configuration["MyAPIUrl"]);
    client.Timeout = new TimeSpan(0, 0, 30);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants.JSONContentType));
}).AddHttpMessageHandler<TokenHandler>();

When the application starts, I get the access token and store in localStorage using the Blazored.LocalStorage package. I have checked the storage in the browser and the token is there. The name of the token is ‘auth0AccessToken’.

The TokenHandler class has the following:

public class TokenHandler : DelegatingHandler
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public TokenHandler(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var accessToken = await _httpContextAccessor.HttpContext.GetTokenAsync("auth0AccessToken");

            request.Headers.Authorization =
                new AuthenticationHeaderValue("Bearer", accessToken);
            return await base.SendAsync(request, cancellationToken);
        }
    }

However, when I debug it, the accessToken is empty. Any thoughts?

The SendAsync method gets called each time I make a request to my custom API so I have to be close.

Hi @MountainTopTech,

Have you seen our blog on Blazor apps? This section details how to call an API with a token.

Also, I would suggest not storing the access token in localstorage. This is considered risky.

Yes, I have read and downloaded that from the blog but it doesn’t address several questions.

My application is a Blazor Server, not Blazor WebAssembly. I think the issue with that blog post is that it doesn’t address how to pass in the token for a Blazor Server application which is why I did it like above. I cannot reference the WebAssembly namespace in a Server application.

Can you provide an example of how to pass in the access token when using a Blazor Server application?

I have a separate API project that uses a typed HttpClient as well. The TokenHandler that I created is supposed to attach the access token to every API request I make (to my custom API) but the token is blank. This could be just the call to GetTokenAsync as I am not even sure what that calls.

Also, from the following link, it says it’s ok to store tokens in localStorage. So, please provide an alternate method?
https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/

Thanks,
Greg

Apologies, I’m not an expert with .net, and it doesn’t look like we have an example for Blazor Server.

Are you referring to the section titled, “You Can Store Refresh Token In Local Storage”? That is explicitly talking about Refresh Tokens. These tokens are not the same as access tokens. More specifically, the article talks about rotating refresh tokens.

The original article I linked shares token storage strategies for Access Tokens.

Can you refer me to someone that might now how to do this? This is really the only thing holding me back from purchasing a subscription. I have to know that my custom API can be secured. I’ve searched pretty much everywhere and can’t find a good example but attaching a token to each request can’t be rocket science. :slight_smile: If I purchase a subscription, what does Standard Support include?

In case anyone wants to see a GREAT example of using the different type of Blazor applications (WebAssembly, Server, Hybrid), please visit this GitHub project. It helped me see what most of the issues were.

https://github.com/grantcolley/blazor-auth0

1 Like

Thanks for sharing that example!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.