I am trying to setup pre-rendering following the guidelines in this documentation article:
Everything works except the custom AuthStateProvider in the course. Loading the token from LocalStorage will not work during pre-rendering:
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var token = await _localStorage.GetItemAsync<string>("authToken");
if (string.IsNullOrEmpty(token))
{
return _anonymous;
}
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(token), "jwtAuthType")));
}
According to the Blazored LocalStorage documentation: Due to pre-rendering in Blazor Server you can't perform any JS interop until the OnAfterRender lifecycle method.
Wrapping this in a try / catch and returning an anonymous works. When the Blazor WebAssembly app is finally loaded the user will be logged in. But for a few seconds you get not authorized messages when you hit a page directly.
How can this custom AuthStateProvider be updated to work with pre-rendering on the server?