Fix admin authorization check - properly parse realm_access claim
The realm_access claim in JWT is a JSON object, not a simple string. Previous string contains check was looking for escaped quotes in wrong format. - Parse realm_access as JSON to extract roles array - Check if 'admin' exists in roles array - Fallback to string contains check if JSON parsing fails - Applied fix in RequireGlobalAdmin policy, TenantValidationMiddleware, and ClubRoleClaimsTransformation Fixes: Admin users getting 401 when trying to create clubs
This commit is contained in:
@@ -53,7 +53,29 @@ builder.Services.AddAuthorizationBuilder()
|
||||
.AddPolicy("RequireGlobalAdmin", policy => policy.RequireAssertion(context =>
|
||||
{
|
||||
var realmAccess = context.User.FindFirst("realm_access")?.Value;
|
||||
return realmAccess != null && realmAccess.Contains("\"admin\"");
|
||||
if (string.IsNullOrEmpty(realmAccess))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(realmAccess);
|
||||
if (doc.RootElement.TryGetProperty("roles", out var rolesElement) &&
|
||||
rolesElement.ValueKind == System.Text.Json.JsonValueKind.Array)
|
||||
{
|
||||
foreach (var role in rolesElement.EnumerateArray())
|
||||
{
|
||||
if (role.GetString() == "admin")
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// If JSON parsing fails, fallback to string contains check
|
||||
return realmAccess.Contains("admin", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
return false;
|
||||
}))
|
||||
.AddPolicy("RequireManager", policy => policy.RequireRole("Manager"))
|
||||
.AddPolicy("RequireMember", policy => policy.RequireRole("Manager", "Member"))
|
||||
|
||||
Reference in New Issue
Block a user