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 @@ +