Files
sor/Server/src/SOR.Admin/Program.cs
T
1b4a652e28 Extract Keycloak group membership as role claims (SOR.Admin)
realm_access.roles only contains directly-assigned realm roles. When the user
is a member of a Keycloak group (e.g. "sor-admin"), the group appears under
the groups claim as "/sor-admin". Parse both sources so group membership
satisfies RequireRole("sor-admin") the same way a realm role would.

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>
2026-04-04 11:02:30 -04:00

252 lines
12 KiB
C#

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using StackExchange.Redis;
using SOR.Admin.Components;
using SOR.Cdn;
using SOR.Database;
using SOR.Database.Contexts;
using SOR.Database.Entities.Identity;
using System.Security.Claims;
using System.Text.Json;
var builder = WebApplication.CreateBuilder(args);
// ── Blazor Server ──────────────────────────────────────────────────────────
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
// Increase SignalR hub message size to support large file uploads (art, 3D models).
// IBrowserFile.OpenReadStream streams through the SignalR hub in Blazor Server.
builder.Services.AddSignalR(opts =>
opts.MaximumReceiveMessageSize = 100 * 1024 * 1024); // 100 MB
// Required for <AuthorizeView> and [Authorize] in Blazor components.
builder.Services.AddCascadingAuthenticationState();
// ── Keycloak OIDC ──────────────────────────────────────────────────────────
// Authentication: cookie for the local session, Keycloak OIDC for the challenge.
// Override Keycloak:ClientSecret via env var (k8s secret): Keycloak__ClientSecret
builder.Services
.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "Keycloak";
})
.AddCookie(options =>
{
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);
})
.AddOpenIdConnect("Keycloak", options =>
{
options.Authority = builder.Configuration["Keycloak:Authority"];
options.ClientId = builder.Configuration["Keycloak:ClientId"];
options.ClientSecret = builder.Configuration["Keycloak:ClientSecret"];
options.ResponseType = "code";
options.SaveTokens = 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
{
NameClaimType = "preferred_username",
// Keycloak doesn't include the client ID in `aud` by default ("account" is used).
// Issuer + signature + realm roles is sufficient for single-realm deployment.
ValidateAudience = false,
};
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 =>
{
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 */ }
return Task.CompletedTask;
},
};
});
// All Blazor pages require the "sor-admin" Keycloak realm role by default.
// Override per-page with [AllowAnonymous] (e.g. the login/challenge shim).
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.RequireRole("sor-admin")
.Build();
});
// Keep UserManager available for account-management pages in the admin panel.
// Sign-in machinery (SignInManager, token providers) is no longer needed —
// authentication is delegated entirely to Keycloak.
builder.Services.AddIdentityCore<Account>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
options.Password.RequireDigit = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequiredLength = 12;
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
})
.AddRoles<IdentityRole<Guid>>()
.AddEntityFrameworkStores<SorIdentityDbContext>();
// ── Razor Pages ────────────────────────────────────────────────────────────
builder.Services.AddRazorPages();
// ── Redis ──────────────────────────────────────────────────────────────────
builder.Services.AddSingleton<IConnectionMultiplexer>(_ =>
{
var redisConnectionString = builder.Configuration.GetConnectionString("Redis") ?? "localhost:6379";
var redisOptions = ConfigurationOptions.Parse(redisConnectionString);
redisOptions.AbortOnConnectFail = false;
return ConnectionMultiplexer.Connect(redisOptions);
});
// ── CDN client ────────────────────────────────────────────────────────────
builder.Services.AddCdnClient(builder.Configuration);
// ── Databases ─────────────────────────────────────────────────────────────
builder.Services.AddIdentityDatabase(builder.Configuration);
builder.Services.AddCatalogDatabase(builder.Configuration);
builder.Services.AddCollectionDatabase(builder.Configuration);
builder.Services.AddBazaarDatabase(builder.Configuration);
builder.Services.AddChatDatabase(builder.Configuration);
builder.Services.AddGameDatabase(builder.Configuration);
builder.Services.AddSupportDatabase(builder.Configuration);
// ── Forwarded headers ─────────────────────────────────────────────────────
// The pod runs plain HTTP behind a TLS-terminating ingress. Without this,
// ASP.NET Core builds the OIDC redirect_uri as "http://..." which Keycloak
// rejects. Clearing KnownNetworks/KnownProxies trusts any upstream proxy —
// safe because the pod is only reachable from within the cluster.
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
// ── HTTP pipeline ─────────────────────────────────────────────────────────
var app = builder.Build();
// Must come before UseAuthentication so the scheme/host are correct when
// the OIDC middleware constructs the redirect_uri.
app.UseForwardedHeaders();
if (!app.Environment.IsDevelopment())
{
// 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.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
// ── Auth endpoints ─────────────────────────────────────────────────────────
// Challenge: cookie auth redirects here when a request is unauthenticated.
// Immediately initiates the Keycloak OIDC flow.
app.MapGet("/auth/challenge", async (HttpContext ctx, [FromQuery] string? returnUrl) =>
{
await ctx.ChallengeAsync("Keycloak",
new AuthenticationProperties { RedirectUri = returnUrl ?? "/" });
}).AllowAnonymous();
// Logout: signs out of the local cookie AND the Keycloak SSO session.
app.MapPost("/auth/logout", async (HttpContext ctx) =>
{
await ctx.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await ctx.SignOutAsync("Keycloak");
}).DisableAntiforgery();
// ── Blazor + Razor Pages ──────────────────────────────────────────────────
app.MapRazorPages();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
// ── Apply pending migrations ───────────────────────────────────────────────
await MigrateAllAsync(app);
app.Run();
// ── Helpers ────────────────────────────────────────────────────────────────
static async Task MigrateAllAsync(WebApplication app)
{
using var scope = app.Services.CreateScope();
var sp = scope.ServiceProvider;
await sp.GetRequiredService<SorIdentityDbContext>().Database.MigrateAsync();
await sp.GetRequiredService<CatalogDbContext>().Database.MigrateAsync();
await sp.GetRequiredService<CollectionDbContext>().Database.MigrateAsync();
await sp.GetRequiredService<BazaarDbContext>().Database.MigrateAsync();
await sp.GetRequiredService<ChatDbContext>().Database.MigrateAsync();
await sp.GetRequiredService<GameDbContext>().Database.MigrateAsync();
await sp.GetRequiredService<SupportDbContext>().Database.MigrateAsync();
}