Fix Keycloak role extraction: use UserInfo endpoint (SOR.Admin)
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 <noreply@anthropic.com> Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -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<SupportDbContext>().Database.MigrateAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the Keycloak access token (already validated by OIDC middleware) and
|
||||
/// adds realm_access.roles entries as <see cref="ClaimTypes.Role"/> claims so that
|
||||
/// [Authorize(Roles = "admin")] and <AuthorizeView Roles="admin"> work normally.
|
||||
/// </summary>
|
||||
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 */ }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user