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:
@@ -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<GameDbContext>().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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" />
|
||||
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" />
|
||||
|
||||
<!-- Design-time only: enables 'dotnet ef migrations add' targeting this project -->
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
|
||||
|
||||
Reference in New Issue
Block a user