I’m building a Blazor App, this app use JWT for token generation and refresh token.
I created an extension class called: CustomAuthenticationStateProviderService
public class CustomAuthenticationStateProviderService : AuthenticationStateProvider
{
private readonly IJSRuntime _jsRuntime;
private readonly HttpClient _httpClient;
public CustomAuthenticationStateProviderService(HttpClient httpClient, IJSRuntime jSRuntime)
{
_httpClient = httpClient;
_jsRuntime = jSRuntime;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var token = await _jsRuntime.InvokeAsync<string>("sessionStorage.getItem", "jwtToken");
var identity = string.IsNullOrEmpty(token)
? new ClaimsIdentity()
: new ClaimsIdentity(ParseClaimsFromToken(token), "jwt");
return new AuthenticationState(new ClaimsPrincipal(identity));
}
public void MarkUserAsAuthenticated(string token)
{
var identity = new ClaimsIdentity(ParseClaimsFromToken(token), "jwt");
var user = new ClaimsPrincipal(identity);
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(user)));
}
public void MarkUserAsLoggedOut()
{
var identity = new ClaimsIdentity();
var user = new ClaimsPrincipal(identity);
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(user)));
}
public IEnumerable<Claim> ParseClaimsFromToken(string jwt)
{
var claims = new List<Claim>();
var payload = jwt.Split('.')[1];
var jsonBytes = ParseBase64WithoutPadding(payload);
var keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, string>>(jsonBytes);
keyValuePairs.TryGetValue(ClaimTypes.NameIdentifier, out var nameIdentifier);
if (nameIdentifier != null)
{
claims.Add(new Claim(ClaimTypes.NameIdentifier, nameIdentifier.ToString()));
}
keyValuePairs.TryGetValue(ClaimTypes.Email, out var email);
if (email != null)
{
claims.Add(new Claim(ClaimTypes.Email, email.ToString()));
}
return claims;
}
private byte[] ParseBase64WithoutPadding(string base64)
{
switch (base64.Length % 4)
{
case 2: base64 += "=="; break;
case 3: base64 += "="; break;
}
return Convert.FromBase64String(base64);
}
}
Program.cs
builder.Services.AddScoped<AuthenticationStateProvider,CustomAuthenticationStateProviderService>();
And this is the error when run the application
I already try to add this line of code in App.razor component
@rendermode @(new InteractiveServerRenderMode(prerender: true))
But is not working
1