feat: enhance JWT token parsing to support multiple role claims
All checks were successful
Build and Deploy / build (push) Successful in 2m20s
All checks were successful
Build and Deploy / build (push) Successful in 2m20s
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
using System.IdentityModel.Tokens.Jwt;
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Blazored.LocalStorage;
|
using Blazored.LocalStorage;
|
||||||
@@ -27,12 +27,53 @@ public class ApiAuthenticationStateProvider : AuthenticationStateProvider
|
|||||||
var handler = new JwtSecurityTokenHandler();
|
var handler = new JwtSecurityTokenHandler();
|
||||||
var token = handler.ReadJwtToken(savedToken);
|
var token = handler.ReadJwtToken(savedToken);
|
||||||
|
|
||||||
|
// Parse the token payload to handle array-based roles
|
||||||
|
var claims = new List<Claim>();
|
||||||
|
|
||||||
var AuthenticationState = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(token.Claims, "jwt")));
|
foreach (var claim in token.Claims)
|
||||||
|
{
|
||||||
return AuthenticationState;
|
// 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 (Exception ex)
|
}
|
||||||
|
}
|
||||||
|
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(claims, "jwt")));
|
||||||
|
|
||||||
|
return authenticationState;
|
||||||
|
}
|
||||||
|
catch
|
||||||
{
|
{
|
||||||
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
|
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user