Fix role claim mapping: OnTicketReceived + JsonWebTokenHandler (SOR.Admin)

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 <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-04-04 11:26:24 -04:00
co-authored by Claude Happy
parent 1b4a652e28
commit 20e5f5f212
2 changed files with 38 additions and 42 deletions
+37 -42
View File
@@ -6,6 +6,7 @@ using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using StackExchange.Redis; using StackExchange.Redis;
using SOR.Admin.Components; using SOR.Admin.Components;
@@ -70,50 +71,15 @@ builder.Services
}; };
options.Events = new OpenIdConnectEvents options.Events = new OpenIdConnectEvents
{ {
// The access token is in-process — no extra HTTP call. // OnTicketReceived fires after SaveTokens, so the access token is
// Decode its payload (already validated) to extract realm_access.roles // guaranteed to be in ctx.Properties. Use JsonWebTokenHandler to decode
// and add them as ClaimTypes.Role so [Authorize(Roles="admin")] works. // it (no re-validation needed — OIDC middleware already validated it).
OnTokenValidated = ctx => OnTicketReceived = ctx =>
{ {
if (ctx.Principal?.Identity is not ClaimsIdentity identity) return Task.CompletedTask; if (ctx.Principal?.Identity is not ClaimsIdentity identity) return Task.CompletedTask;
var raw = ctx.TokenEndpointResponse?.AccessToken; var accessToken = ctx.Properties?.GetTokenValue("access_token");
if (string.IsNullOrEmpty(raw)) return Task.CompletedTask; if (string.IsNullOrEmpty(accessToken)) return Task.CompletedTask;
AddKeycloakRoleClaims(identity, accessToken);
// 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 */ }
return Task.CompletedTask; return Task.CompletedTask;
}, },
}; };
@@ -249,3 +215,32 @@ static async Task MigrateAllAsync(WebApplication app)
await sp.GetRequiredService<GameDbContext>().Database.MigrateAsync(); await sp.GetRequiredService<GameDbContext>().Database.MigrateAsync();
await sp.GetRequiredService<SupportDbContext>().Database.MigrateAsync(); await sp.GetRequiredService<SupportDbContext>().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));
}
}
}
+1
View File
@@ -6,6 +6,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" />
<!-- Design-time only: enables 'dotnet ef migrations add' targeting this project --> <!-- Design-time only: enables 'dotnet ef migrations add' targeting this project -->
<PackageReference Include="Microsoft.EntityFrameworkCore.Design"> <PackageReference Include="Microsoft.EntityFrameworkCore.Design">