feat: enhance JWT token parsing to support multiple role claims
All checks were successful
Build and Deploy / build (push) Successful in 2m20s

This commit is contained in:
masoodafar-web
2025-12-08 02:57:14 +03:30
parent 5a4774b1f3
commit f00ade566c

View File

@@ -1,4 +1,4 @@
using System.IdentityModel.Tokens.Jwt;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text.Json;
using Blazored.LocalStorage;
@@ -27,12 +27,53 @@ public class ApiAuthenticationStateProvider : AuthenticationStateProvider
var handler = new JwtSecurityTokenHandler();
var token = handler.ReadJwtToken(savedToken);
// Parse the token payload to handle array-based roles
var claims = new List<Claim>();
foreach (var claim in token.Claims)
{
// Handle role claims specially to support multiple roles
if (claim.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" ||
claim.Type == ClaimTypes.Role ||
claim.Type == "role")
{
// Check if the value is a JSON array
if (claim.Value.TrimStart().StartsWith("["))
{
try
{
var roles = JsonSerializer.Deserialize<string[]>(claim.Value);
if (roles != null)
{
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
}
}
catch
{
// If parsing fails, add as single claim
claims.Add(new Claim(ClaimTypes.Role, claim.Value));
}
}
else
{
// Single role value
claims.Add(new Claim(ClaimTypes.Role, claim.Value));
}
}
else
{
claims.Add(claim);
}
}
var AuthenticationState = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(token.Claims, "jwt")));
var authenticationState = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt")));
return AuthenticationState;
return authenticationState;
}
catch (Exception ex)
catch
{
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
}