From 6f4c72958280de3592b99b9e5528ef310ee1bf7f Mon Sep 17 00:00:00 2001 From: dingo Date: Sat, 4 Apr 2026 09:36:33 -0400 Subject: [PATCH] Fix Keycloak role extraction: use UserInfo endpoint (SOR.Admin) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OnTokenValidated + manual access-token base64 decode was unreliable. Switch to GetClaimsFromUserInfoEndpoint=true and extract realm_access.roles in OnUserInformationReceived where the UserInfo JSON is already parsed into ctx.User (JsonDocument) — no manual JWT decoding needed. Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- Server/src/SOR.Admin/Program.cs | 45 ++++++++++----------------------- 1 file changed, 13 insertions(+), 32 deletions(-) diff --git a/Server/src/SOR.Admin/Program.cs b/Server/src/SOR.Admin/Program.cs index 7c7820a..2d6cf14 100644 --- a/Server/src/SOR.Admin/Program.cs +++ b/Server/src/SOR.Admin/Program.cs @@ -53,6 +53,9 @@ builder.Services options.ClientSecret = builder.Configuration["Keycloak:ClientSecret"]; options.ResponseType = "code"; options.SaveTokens = true; + // Fetch roles from the UserInfo endpoint — Keycloak always includes + // realm_access.roles there, so we don't need ID-token protocol mappers. + options.GetClaimsFromUserInfoEndpoint = true; // Don't map inbound claims — Keycloak uses non-standard claim names. options.MapInboundClaims = false; options.TokenValidationParameters = new TokenValidationParameters @@ -64,14 +67,18 @@ builder.Services }; options.Events = new OpenIdConnectEvents { - OnTokenValidated = ctx => + // UserInfo response arrives as a JsonElement; extract realm_access.roles + // and add them as ClaimTypes.Role so [Authorize(Roles="admin")] works. + OnUserInformationReceived = ctx => { - // Extract Keycloak realm roles from the access token and add them as - // ClaimTypes.Role so that [Authorize(Roles = "admin")] works normally. - if (ctx.Principal?.Identity is ClaimsIdentity identity - && ctx.TokenEndpointResponse?.AccessToken is { Length: > 0 } accessToken) + if (ctx.Principal?.Identity is not ClaimsIdentity identity) return Task.CompletedTask; + if (!ctx.User.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()) { - AddRealmRoleClaims(identity, accessToken); + var r = role.GetString(); + if (r is not null) + identity.AddClaim(new Claim(ClaimTypes.Role, r)); } return Task.CompletedTask; }, @@ -202,29 +209,3 @@ static async Task MigrateAllAsync(WebApplication app) await sp.GetRequiredService().Database.MigrateAsync(); } -/// -/// Decodes the Keycloak access token (already validated by OIDC middleware) and -/// adds realm_access.roles entries as claims so that -/// [Authorize(Roles = "admin")] and work normally. -/// -static void AddRealmRoleClaims(ClaimsIdentity identity, string accessToken) -{ - // JWT: header.payload.signature — payload is base64url encoded JSON. - var parts = accessToken.Split('.'); - if (parts.Length != 3) return; - try - { - 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; - if (!realmAccess.TryGetProperty("roles", out var rolesEl)) return; - foreach (var role in rolesEl.EnumerateArray()) - { - var r = role.GetString(); - if (r is not null) - identity.AddClaim(new Claim(ClaimTypes.Role, r)); - } - } - catch { /* malformed access token — ignore */ } -}