Can't silently refresh security token, Azure B2C, Blazor WASM

Viewed 229

I'm making a Blazor WASM app and followed these instructions to enable authentication.

Secure and ASP.NET Core Blazor WASM

I added one line to the Program.cs file...

options.ProviderOptions.Cache.CacheLocation = "localStorage";

It seems to work - logging in, redirecting when not logged in, etc. But when the token expires after about an hour all my network calls through the injected HttpClient fail with AccessTokenNotAvailableException. This is super annoying. Shouldn't the token get refreshed automatically with NO user interaction necessary? Or does refreshing a token always require user interaction?

My workaround is to catch these exceptions and call Redirect like this. This introduces a bunch of UI the user doesn't expect and the redirect doesn't return the user to the place where the security problem occurred.

try {
    var result = await _httpClient.GetFromJsonAsync...
    return result;
}
catch (AccessTokenNotAvailableException e) {
    e.Redirect();
    return null;
}

My network calls happen through a Scoped service called ServerStorage. The HTTP client is initialized in Program.cs.

public ServerStorage(HttpClient httpClient) {
    this._httpClient = httpClient;
}

builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("GroceriesWasmApp.ServerAPI"));
0 Answers
Related