Extract Keycloak group membership as role claims (SOR.Admin)
realm_access.roles only contains directly-assigned realm roles. When the user
is a member of a Keycloak group (e.g. "sor-admin"), the group appears under
the groups claim as "/sor-admin". Parse both sources so group membership
satisfies RequireRole("sor-admin") the same way a realm role would.
Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -87,13 +87,30 @@ builder.Services
|
||||
var padding = (4 - parts[1].Length % 4) % 4;
|
||||
var base64 = parts[1].Replace('-', '+').Replace('_', '/') + new string('=', padding);
|
||||
using var doc = JsonDocument.Parse(Convert.FromBase64String(base64));
|
||||
if (!doc.RootElement.TryGetProperty("realm_access", out var realmAccess)) return Task.CompletedTask;
|
||||
if (!realmAccess.TryGetProperty("roles", out var roles)) return Task.CompletedTask;
|
||||
foreach (var role in roles.EnumerateArray())
|
||||
var root = doc.RootElement;
|
||||
|
||||
// Realm roles: realm_access.roles → ["sor-admin", ...]
|
||||
if (root.TryGetProperty("realm_access", out var realmAccess)
|
||||
&& realmAccess.TryGetProperty("roles", out var realmRoles))
|
||||
{
|
||||
var r = role.GetString();
|
||||
if (r is not null)
|
||||
identity.AddClaim(new Claim(ClaimTypes.Role, r));
|
||||
foreach (var role in realmRoles.EnumerateArray())
|
||||
{
|
||||
var r = role.GetString();
|
||||
if (r is not null)
|
||||
identity.AddClaim(new Claim(ClaimTypes.Role, r));
|
||||
}
|
||||
}
|
||||
|
||||
// Group membership: groups → ["/sor-admin", ...] (leading slash stripped).
|
||||
// Keycloak groups appear here when a "groups" protocol mapper is configured.
|
||||
if (root.TryGetProperty("groups", out var groups))
|
||||
{
|
||||
foreach (var group in groups.EnumerateArray())
|
||||
{
|
||||
var g = group.GetString()?.TrimStart('/');
|
||||
if (!string.IsNullOrEmpty(g))
|
||||
identity.AddClaim(new Claim(ClaimTypes.Role, g));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { /* malformed token — no roles added, auth will 403 */ }
|
||||
|
||||
Reference in New Issue
Block a user