From f00ade566c14e95b444954a57a9ffc06e4917b5f Mon Sep 17 00:00:00 2001 From: masoodafar-web Date: Mon, 8 Dec 2025 02:57:14 +0330 Subject: [PATCH] feat: enhance JWT token parsing to support multiple role claims --- .../ApiAuthenticationStateProvider.cs | 49 +++++++++++++++++-- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/src/BackOffice/Common/Utilities/ApiAuthenticationStateProvider.cs b/src/BackOffice/Common/Utilities/ApiAuthenticationStateProvider.cs index 4a4304a..c89dd8c 100644 --- a/src/BackOffice/Common/Utilities/ApiAuthenticationStateProvider.cs +++ b/src/BackOffice/Common/Utilities/ApiAuthenticationStateProvider.cs @@ -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(); + + 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(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())); }