I'm struggling for days to make the JWT authentication working in my .NET 6.0 Blazor Server app! I'm getting this error message:
InvalidOperationException: JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendered. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method.
I Created this class:
public class CustomAuthStateProvider : AuthenticationStateProvider
{
private readonly ILocalStorageService _localStorage;
private readonly HttpClient _http;
public CustomAuthStateProvider(ILocalStorageService localStorage, HttpClient http)
{
_localStorage = localStorage;
_http = http;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
string token = await _localStorage.GetItemAsStringAsync("token"); //The exception is thrown at this line
var identity = new ClaimsIdentity();
...
return state;
}
public static IEnumerable<Claim> ParseClaimsFromJwt(string jwt)
{
...
}
private static byte[] ParseBase64WithoutPadding(string base64)
{
....
}
}
My Program.cs is the default one, I just added those services:
builder.Services.AddHttpClient();
builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();
builder.Services.AddAuthorizationCore();
builder.Services.AddBlazoredLocalStorage();
The exception is thrown at this line: string token = await _localStorage.GetItemAsStringAsync("token");
I'm trying to use Blazored.LocalStorage for the local storage, but I also tried with ProtectedLocalStorage and got the same error!
Can you please help me on how to fix this exception?