From 20e5f5f2124fc420d0a221a19cbc729a025571ac Mon Sep 17 00:00:00 2001 From: dingo Date: Sat, 4 Apr 2026 11:26:24 -0400 Subject: [PATCH] Fix role claim mapping: OnTicketReceived + JsonWebTokenHandler (SOR.Admin) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ctx.TokenEndpointResponse?.AccessToken in OnTokenValidated is not reliably populated; if null the silent catch left the principal with no role claims, causing 403 on every request despite successful Keycloak auth. Switch to OnTicketReceived which fires after SaveTokens — access token is guaranteed present via ctx.Properties.GetTokenValue("access_token"). Use JsonWebTokenHandler.ReadJsonWebToken() instead of manual base64 decode to eliminate silent parse failures. Extracts both realm_access.roles and groups claims so either Keycloak assignment style works. 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 | 79 +++++++++++++-------------- Server/src/SOR.Admin/SOR.Admin.csproj | 1 + 2 files changed, 38 insertions(+), 42 deletions(-) diff --git a/Server/src/SOR.Admin/Program.cs b/Server/src/SOR.Admin/Program.cs index 20e5a73..14d353f 100644 --- a/Server/src/SOR.Admin/Program.cs +++ b/Server/src/SOR.Admin/Program.cs @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; +using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; using StackExchange.Redis; using SOR.Admin.Components; @@ -70,50 +71,15 @@ builder.Services }; options.Events = new OpenIdConnectEvents { - // The access token is in-process — no extra HTTP call. - // Decode its payload (already validated) to extract realm_access.roles - // and add them as ClaimTypes.Role so [Authorize(Roles="admin")] works. - OnTokenValidated = ctx => + // OnTicketReceived fires after SaveTokens, so the access token is + // guaranteed to be in ctx.Properties. Use JsonWebTokenHandler to decode + // it (no re-validation needed — OIDC middleware already validated it). + OnTicketReceived = ctx => { if (ctx.Principal?.Identity is not ClaimsIdentity identity) return Task.CompletedTask; - var raw = ctx.TokenEndpointResponse?.AccessToken; - if (string.IsNullOrEmpty(raw)) return Task.CompletedTask; - - // JWT payload is the middle base64url segment. - var parts = raw.Split('.'); - if (parts.Length != 3) return Task.CompletedTask; - 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)); - 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)) - { - 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 */ } + var accessToken = ctx.Properties?.GetTokenValue("access_token"); + if (string.IsNullOrEmpty(accessToken)) return Task.CompletedTask; + AddKeycloakRoleClaims(identity, accessToken); return Task.CompletedTask; }, }; @@ -249,3 +215,32 @@ static async Task MigrateAllAsync(WebApplication app) await sp.GetRequiredService().Database.MigrateAsync(); await sp.GetRequiredService().Database.MigrateAsync(); } + +// Decodes the Keycloak access token and adds realm_access.roles and groups +// as ClaimTypes.Role claims. Called from OnTicketReceived where SaveTokens +// has already run, so the token is guaranteed present in auth properties. +static void AddKeycloakRoleClaims(ClaimsIdentity identity, string accessToken) +{ + var jwt = new JsonWebTokenHandler().ReadJsonWebToken(accessToken); + + // Realm roles: realm_access.roles → ["sor-admin", ...] + if (jwt.TryGetPayloadValue("realm_access", out JsonElement realmAccess) + && realmAccess.TryGetProperty("roles", out var realmRoles)) + { + 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). + if (jwt.TryGetPayloadValue("groups", out JsonElement groups)) + { + foreach (var group in groups.EnumerateArray()) + { + var g = group.GetString()?.TrimStart('/'); + if (!string.IsNullOrEmpty(g)) identity.AddClaim(new Claim(ClaimTypes.Role, g)); + } + } +} diff --git a/Server/src/SOR.Admin/SOR.Admin.csproj b/Server/src/SOR.Admin/SOR.Admin.csproj index f936b25..8c10a76 100644 --- a/Server/src/SOR.Admin/SOR.Admin.csproj +++ b/Server/src/SOR.Admin/SOR.Admin.csproj @@ -6,6 +6,7 @@ +