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:
@@ -54,13 +54,36 @@ public class ClubRoleClaimsTransformation : IClaimsTransformation
|
||||
return Task.FromResult(principal);
|
||||
}
|
||||
|
||||
// --- NEW: Skip DB role lookup if user is a global admin ---
|
||||
var realmAccess = principal.FindFirst("realm_access")?.Value;
|
||||
if (!string.IsNullOrEmpty(realmAccess) && realmAccess.Contains("\"admin\"", StringComparison.OrdinalIgnoreCase))
|
||||
// --- NEW: Skip DB role lookup if user is a global admin ---
|
||||
var realmAccess = principal.FindFirst("realm_access")?.Value;
|
||||
if (!string.IsNullOrEmpty(realmAccess) && IsAdminUser(realmAccess))
|
||||
{
|
||||
return Task.FromResult(principal);
|
||||
}
|
||||
// ---------------------------------------------------------
|
||||
|
||||
static bool IsAdminUser(string realmAccess)
|
||||
{
|
||||
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)
|
||||
{
|
||||
return Task.FromResult(principal);
|
||||
foreach (var role in rolesElement.EnumerateArray())
|
||||
{
|
||||
if (role.GetString()?.Equals("admin", StringComparison.OrdinalIgnoreCase) == true)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// ---------------------------------------------------------
|
||||
}
|
||||
catch
|
||||
{
|
||||
// If JSON parsing fails, fallback to string contains check
|
||||
return realmAccess.Contains("admin", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Look up the user's role in the database for the requested tenant
|
||||
_httpContextAccessor.HttpContext!.Items["TenantId"] = tenantId;
|
||||
|
||||
Reference in New Issue
Block a user