Call Protected APIs from a Blazor Web App

Calling a protected API from a .NET 8 Blazor Web App can be a bit tricky. Let’s see what the problems are and how to solve them.
Read more…

:writing_hand:t2: Brought to you by @andrea.chiarelli

Your feedback and questions are important – feel free to express them!

After <<the configured access token liftime>> minutes, the api-calls fails, with “token expired”.
If i log out and login in the blazor server app, it starts working again.

How can I instead do access-token refresh for active sessions?

It thought this should do it for me automatically:
_httpContextAccessor.HttpContext!.GetTokenAsync("access_token");

But no, that just keeps returning the same (expired) token as long as the user is logged in…

update:

I found the UseRefreshTokens in the docs. Why this isnt true by default, who know?

    
    .WithAccessToken(options =>
    {
        options.Audience = builder.Configuration["Auth0:Audience"];
        options.UseRefreshTokens = true;
    });

The problem is, still not working. Access tokens are not refreshed.

Update 2:
I verified that “use refresh tokens” , “allow offline access” is checkd in the settings.
I have also added the scope “offline_access”.

Still not working.

@robertino.calcaterra please advice.

Hey @sebastian4,
With options.UseRefreshTokens = true; you don’t need to specify the offline_access scope. The SDK does it for you.
As far as I can see, with the setup you described, refresh tokens should work.
Make sure to log out and log in again after you make your settings on your Auth0 dashboard.
This article explains how to use refresh tokens in an ASP.NET Core application and includes a working sample project, but basically it does what you already did.
Have you had a chance to take a look at the HTTP requests exchanged between your application and your Auth0 tenant to see if actually a refresh token is requested and obtained?