diff --git a/Server/src/SOR.Admin/Program.cs b/Server/src/SOR.Admin/Program.cs index 2d6cf14..6ceceef 100644 --- a/Server/src/SOR.Admin/Program.cs +++ b/Server/src/SOR.Admin/Program.cs @@ -41,8 +41,10 @@ builder.Services }) .AddCookie(options => { - // Redirect to the challenge shim instead of a password form. 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.ExpireTimeSpan = TimeSpan.FromHours(8); }) @@ -53,9 +55,10 @@ 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 call the UserInfo endpoint — that extra pod→Keycloak HTTPS hop + // was throwing and landing on /Error, which is itself protected and caused + // 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. options.MapInboundClaims = false; options.TokenValidationParameters = new TokenValidationParameters @@ -67,19 +70,33 @@ builder.Services }; 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. - OnUserInformationReceived = ctx => + OnTokenValidated = ctx => { 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()) + 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 r = role.GetString(); - if (r is not null) - identity.AddClaim(new Claim(ClaimTypes.Role, r)); + 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 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; }, }; @@ -156,7 +173,14 @@ app.UseForwardedHeaders(); 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(); } @@ -208,4 +232,3 @@ static async Task MigrateAllAsync(WebApplication app) await sp.GetRequiredService().Database.MigrateAsync(); await sp.GetRequiredService().Database.MigrateAsync(); } -