Fix Keycloak auth redirect loop in SOR.Admin (3 bugs)
1. Remove GetClaimsFromUserInfoEndpoint=true — the extra pod→Keycloak HTTPS
call was throwing (SSL/network error from within the cluster), which hit the
exception handler and triggered a protected /Error redirect, starting the loop.
Roles are extracted from the access token payload instead (no HTTP call needed).
2. Set AccessDeniedPath=PathString.Empty on the cookie handler — the default
/Account/AccessDenied path doesn't exist in this app, causing the cookie
middleware to redirect there infinitely. Empty path returns 403 directly.
3. Replace UseExceptionHandler("/Error") with an inline handler — /Error is a
protected Blazor route; redirecting to it while unauthenticated re-triggered
the auth challenge, feeding the redirect loop. Inline handler returns 500
without any redirect.
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:
@@ -41,8 +41,10 @@ builder.Services
|
|||||||
})
|
})
|
||||||
.AddCookie(options =>
|
.AddCookie(options =>
|
||||||
{
|
{
|
||||||
// Redirect to the challenge shim instead of a password form.
|
|
||||||
options.LoginPath = "/auth/challenge";
|
options.LoginPath = "/auth/challenge";
|
||||||
|
// Explicit empty path: return 403 directly instead of redirecting to the
|
||||||
|
// default /Account/AccessDenied (which doesn't exist and causes a loop).
|
||||||
|
options.AccessDeniedPath = PathString.Empty;
|
||||||
options.SlidingExpiration = true;
|
options.SlidingExpiration = true;
|
||||||
options.ExpireTimeSpan = TimeSpan.FromHours(8);
|
options.ExpireTimeSpan = TimeSpan.FromHours(8);
|
||||||
})
|
})
|
||||||
@@ -53,9 +55,10 @@ builder.Services
|
|||||||
options.ClientSecret = builder.Configuration["Keycloak:ClientSecret"];
|
options.ClientSecret = builder.Configuration["Keycloak:ClientSecret"];
|
||||||
options.ResponseType = "code";
|
options.ResponseType = "code";
|
||||||
options.SaveTokens = true;
|
options.SaveTokens = true;
|
||||||
// Fetch roles from the UserInfo endpoint — Keycloak always includes
|
// Don't call the UserInfo endpoint — that extra pod→Keycloak HTTPS hop
|
||||||
// realm_access.roles there, so we don't need ID-token protocol mappers.
|
// was throwing and landing on /Error, which is itself protected and caused
|
||||||
options.GetClaimsFromUserInfoEndpoint = true;
|
// the 20-redirect loop. The access token already contains realm_access.roles.
|
||||||
|
options.GetClaimsFromUserInfoEndpoint = false;
|
||||||
// Don't map inbound claims — Keycloak uses non-standard claim names.
|
// Don't map inbound claims — Keycloak uses non-standard claim names.
|
||||||
options.MapInboundClaims = false;
|
options.MapInboundClaims = false;
|
||||||
options.TokenValidationParameters = new TokenValidationParameters
|
options.TokenValidationParameters = new TokenValidationParameters
|
||||||
@@ -67,19 +70,33 @@ builder.Services
|
|||||||
};
|
};
|
||||||
options.Events = new OpenIdConnectEvents
|
options.Events = new OpenIdConnectEvents
|
||||||
{
|
{
|
||||||
// UserInfo response arrives as a JsonElement; extract realm_access.roles
|
// 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.
|
// and add them as ClaimTypes.Role so [Authorize(Roles="admin")] works.
|
||||||
OnUserInformationReceived = ctx =>
|
OnTokenValidated = ctx =>
|
||||||
{
|
{
|
||||||
if (ctx.Principal?.Identity is not ClaimsIdentity identity) return Task.CompletedTask;
|
if (ctx.Principal?.Identity is not ClaimsIdentity identity) return Task.CompletedTask;
|
||||||
if (!ctx.User.RootElement.TryGetProperty("realm_access", out var realmAccess)) return Task.CompletedTask;
|
var raw = ctx.TokenEndpointResponse?.AccessToken;
|
||||||
if (!realmAccess.TryGetProperty("roles", out var roles)) return Task.CompletedTask;
|
if (string.IsNullOrEmpty(raw)) return Task.CompletedTask;
|
||||||
foreach (var role in roles.EnumerateArray())
|
|
||||||
|
// JWT payload is the middle base64url segment.
|
||||||
|
var parts = raw.Split('.');
|
||||||
|
if (parts.Length != 3) return Task.CompletedTask;
|
||||||
|
try
|
||||||
{
|
{
|
||||||
var r = role.GetString();
|
var padding = (4 - parts[1].Length % 4) % 4;
|
||||||
if (r is not null)
|
var base64 = parts[1].Replace('-', '+').Replace('_', '/') + new string('=', padding);
|
||||||
identity.AddClaim(new Claim(ClaimTypes.Role, r));
|
using var doc = JsonDocument.Parse(Convert.FromBase64String(base64));
|
||||||
|
if (!doc.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())
|
||||||
|
{
|
||||||
|
var r = role.GetString();
|
||||||
|
if (r is not null)
|
||||||
|
identity.AddClaim(new Claim(ClaimTypes.Role, r));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
catch { /* malformed token — no roles added, auth will 403 */ }
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -156,7 +173,14 @@ app.UseForwardedHeaders();
|
|||||||
|
|
||||||
if (!app.Environment.IsDevelopment())
|
if (!app.Environment.IsDevelopment())
|
||||||
{
|
{
|
||||||
app.UseExceptionHandler("/Error");
|
// Inline handler — avoids re-executing to a protected Blazor route (/Error),
|
||||||
|
// which would trigger an auth challenge and cause a redirect loop.
|
||||||
|
app.UseExceptionHandler(err => err.Run(async ctx =>
|
||||||
|
{
|
||||||
|
ctx.Response.StatusCode = 500;
|
||||||
|
ctx.Response.ContentType = "text/plain";
|
||||||
|
await ctx.Response.WriteAsync("An internal server error occurred.");
|
||||||
|
}));
|
||||||
app.UseHsts();
|
app.UseHsts();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,4 +232,3 @@ 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();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user