From fa695649f68e6aa382d3b18bb779dc874c6d92de Mon Sep 17 00:00:00 2001 From: dingo Date: Sat, 4 Apr 2026 08:46:27 -0400 Subject: [PATCH] Replace SOR.Admin email/password login with Keycloak OIDC Admin panel now delegates authentication entirely to Keycloak using the Authorization Code flow. The local Identity password form and IdentityRevalidatingAuthenticationStateProvider are removed. Access requires the "admin" Keycloak realm role, mirroring the game's role-based auth model. - Program.cs: AddOpenIdConnect("Keycloak") with cookie session; /auth/challenge triggers the OIDC flow; /auth/logout signs out of both cookie and Keycloak SSO - Login.razor: replaced HTML form with an immediate redirect to /auth/challenge - IdentityRevalidatingAuthenticationStateProvider.cs: deleted (no longer needed) - appsettings.json: Keycloak:Authority / ClientId / ClientSecret section added - Directory.Packages.props: pinned Microsoft.AspNetCore.Authentication.OpenIdConnect 8.0.0 - SOR.Admin.csproj: added OpenIdConnect package reference Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- Server/Directory.Packages.props | 1 + .../SOR.Admin/Components/Pages/Login.razor | 45 +---- ...RevalidatingAuthenticationStateProvider.cs | 44 ----- Server/src/SOR.Admin/Program.cs | 175 ++++++++++-------- Server/src/SOR.Admin/SOR.Admin.csproj | 2 + Server/src/SOR.Admin/appsettings.json | 14 +- 6 files changed, 116 insertions(+), 165 deletions(-) delete mode 100644 Server/src/SOR.Admin/IdentityRevalidatingAuthenticationStateProvider.cs diff --git a/Server/Directory.Packages.props b/Server/Directory.Packages.props index d66b1cf..8acb406 100644 --- a/Server/Directory.Packages.props +++ b/Server/Directory.Packages.props @@ -18,6 +18,7 @@ + diff --git a/Server/src/SOR.Admin/Components/Pages/Login.razor b/Server/src/SOR.Admin/Components/Pages/Login.razor index 95eedef..49be2b5 100644 --- a/Server/src/SOR.Admin/Components/Pages/Login.razor +++ b/Server/src/SOR.Admin/Components/Pages/Login.razor @@ -1,45 +1,14 @@ @page "/login" @attribute [AllowAnonymous] -@* Static SSR — no rendermode, keeps login available without a SignalR connection. *@ +@inject NavigationManager Nav -Sign In – SOR Admin - -
-
-
-

- SOR Admin -

-

Sign in to continue

- - @if (Error == "invalid") - { -
Invalid email or password.
- } - else if (Error == "locked") - { -
Account locked — try again later.
- } - -
- - -
- - -
-
- - -
- -
-
-
-
+@* Static SSR — no rendermode, stays available without a SignalR connection. *@ @code { [SupplyParameterFromQuery] public string? ReturnUrl { get; set; } - [SupplyParameterFromQuery] public string? Error { get; set; } + + protected override void OnInitialized() => + Nav.NavigateTo( + $"/auth/challenge?returnUrl={Uri.EscapeDataString(ReturnUrl ?? "/")}", + forceLoad: true); } diff --git a/Server/src/SOR.Admin/IdentityRevalidatingAuthenticationStateProvider.cs b/Server/src/SOR.Admin/IdentityRevalidatingAuthenticationStateProvider.cs deleted file mode 100644 index e7e7b03..0000000 --- a/Server/src/SOR.Admin/IdentityRevalidatingAuthenticationStateProvider.cs +++ /dev/null @@ -1,44 +0,0 @@ -namespace SOR.Admin; - -using Microsoft.AspNetCore.Components.Authorization; -using Microsoft.AspNetCore.Components.Server; -using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.Options; -using SOR.Database.Entities.Identity; - -/// -/// Revalidates the Identity cookie on a schedule while a Blazor Server circuit -/// is open, so that bans or role changes take effect without a page reload. -/// This is the standard pattern from the Blazor Identity scaffolding. -/// -internal sealed class IdentityRevalidatingAuthenticationStateProvider( - ILoggerFactory loggerFactory, - IServiceScopeFactory scopeFactory, - IOptions options) - : RevalidatingServerAuthenticationStateProvider(loggerFactory) -{ - protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(30); - - protected override async Task ValidateAuthenticationStateAsync( - AuthenticationState authenticationState, - CancellationToken cancellationToken) - { - await using var scope = scopeFactory.CreateAsyncScope(); - var userManager = scope.ServiceProvider.GetRequiredService>(); - return await ValidateSecurityStampAsync(userManager, authenticationState.User); - } - - private async Task ValidateSecurityStampAsync( - UserManager userManager, - System.Security.Claims.ClaimsPrincipal principal) - { - var user = await userManager.GetUserAsync(principal); - if (user is null) return false; - if (!userManager.SupportsUserSecurityStamp) return true; - - var principalStamp = principal - .FindFirst(options.Value.ClaimsIdentity.SecurityStampClaimType)?.Value; - var userStamp = await userManager.GetSecurityStampAsync(user); - return principalStamp == userStamp; - } -} diff --git a/Server/src/SOR.Admin/Program.cs b/Server/src/SOR.Admin/Program.cs index adcf883..ca57472 100644 --- a/Server/src/SOR.Admin/Program.cs +++ b/Server/src/SOR.Admin/Program.cs @@ -1,16 +1,19 @@ +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.EntityFrameworkCore; +using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.IdentityModel.Tokens; using StackExchange.Redis; -using SOR.Admin; 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); @@ -25,36 +28,68 @@ builder.Services.AddSignalR(opts => // Required for and [Authorize] in Blazor components. builder.Services.AddCascadingAuthenticationState(); -builder.Services.AddScoped(); -// ── Identity + Cookie Auth ────────────────────────────────────────────────── -builder.Services.AddAuthentication(options => +// ── 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 = IdentityConstants.ApplicationScheme; - options.DefaultSignInScheme = IdentityConstants.ExternalScheme; + options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = "Keycloak"; }) - .AddIdentityCookies(); + .AddCookie(options => + { + // Redirect to the challenge shim instead of a password form. + options.LoginPath = "/auth/challenge"; + 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 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 + { + OnTokenValidated = 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) + { + AddRealmRoleClaims(identity, accessToken); + } + return Task.CompletedTask; + }, + }; + }); -// Redirect to /login instead of the default /Account/Login. -builder.Services.ConfigureApplicationCookie(options => -{ - options.LoginPath = "/login"; - options.AccessDeniedPath = "/login"; - options.SlidingExpiration = true; - options.ExpireTimeSpan = TimeSpan.FromHours(8); -}); - -// All Blazor pages require Admin or SuperAdmin role by default. -// Override per-page with [AllowAnonymous] (login page only). +// All Blazor pages require the "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("Admin", "SuperAdmin") + .RequireRole("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(options => { options.SignIn.RequireConfirmedAccount = false; @@ -66,11 +101,9 @@ builder.Services.AddIdentityCore(options => options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30); }) .AddRoles>() - .AddEntityFrameworkStores() - .AddSignInManager() - .AddDefaultTokenProviders(); + .AddEntityFrameworkStores(); -// ── Razor Pages (used for login/logout form posts) ───────────────────────── +// ── Razor Pages ──────────────────────────────────────────────────────────── builder.Services.AddRazorPages(); // ── Redis ────────────────────────────────────────────────────────────────── @@ -110,36 +143,21 @@ app.UseAuthentication(); app.UseAuthorization(); app.UseAntiforgery(); -// ── Auth endpoints (form POST targets — cookies cannot be set from Blazor) ── +// ── Auth endpoints ───────────────────────────────────────────────────────── -// Login: called by the /login page form. -app.MapPost("/auth/login", async ( - HttpContext ctx, - [FromForm] string email, - [FromForm] string password, - [FromForm] string? returnUrl, - UserManager userManager, - SignInManager signInManager) => +// 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) => { - var user = await userManager.FindByEmailAsync(email); - if (user is not null) - { - var result = await signInManager.PasswordSignInAsync( - user, password, isPersistent: false, lockoutOnFailure: true); - if (result.Succeeded) - return Results.LocalRedirect( - string.IsNullOrWhiteSpace(returnUrl) ? "/" : returnUrl); - if (result.IsLockedOut) - return Results.Redirect("/login?error=locked"); - } - return Results.Redirect("/login?error=invalid"); -}).AllowAnonymous().DisableAntiforgery(); + await ctx.ChallengeAsync("Keycloak", + new AuthenticationProperties { RedirectUri = returnUrl ?? "/" }); +}).AllowAnonymous(); -// Logout: called by the nav menu form. -app.MapPost("/auth/logout", async (SignInManager signInManager) => +// Logout: signs out of the local cookie AND the Keycloak SSO session. +app.MapPost("/auth/logout", async (HttpContext ctx) => { - await signInManager.SignOutAsync(); - return Results.Redirect("/login"); + await ctx.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + await ctx.SignOutAsync("Keycloak"); }).DisableAntiforgery(); // ── Blazor + Razor Pages ────────────────────────────────────────────────── @@ -150,11 +168,10 @@ app.MapRazorComponents() // ── Apply pending migrations ─────────────────────────────────────────────── await MigrateAllAsync(app); -// ── Seed roles and initial SuperAdmin ───────────────────────────────────── -await SeedAsync(app); - app.Run(); +// ── Helpers ──────────────────────────────────────────────────────────────── + static async Task MigrateAllAsync(WebApplication app) { using var scope = app.Services.CreateScope(); @@ -168,35 +185,29 @@ static async Task MigrateAllAsync(WebApplication app) await sp.GetRequiredService().Database.MigrateAsync(); } -static async Task SeedAsync(WebApplication app) +/// +/// Decodes the Keycloak access token (already validated by OIDC middleware) and +/// adds realm_access.roles entries as claims so that +/// [Authorize(Roles = "admin")] and work normally. +/// +static void AddRealmRoleClaims(ClaimsIdentity identity, string accessToken) { - using var scope = app.Services.CreateScope(); - var roleManager = scope.ServiceProvider.GetRequiredService>>(); - var userManager = scope.ServiceProvider.GetRequiredService>(); - var cfg = scope.ServiceProvider.GetRequiredService(); - - foreach (var role in new[] { "SuperAdmin", "Admin", "player", "moderator", "card_builder" }) + // JWT: header.payload.signature — payload is base64url encoded JSON. + var parts = accessToken.Split('.'); + if (parts.Length != 3) return; + try { - if (!await roleManager.RoleExistsAsync(role)) - await roleManager.CreateAsync(new IdentityRole(role)); - } - - // Create the first SuperAdmin if none exists. - // Override via appsettings / env vars: Admin:Email Admin:Password - var email = cfg["Admin:Email"] ?? "admin@sor.local"; - var password = cfg["Admin:Password"] ?? "SOR!Admin#Forge$2026@AeternalisGames%Prod"; - - if (await userManager.FindByEmailAsync(email) is null) - { - var account = new Account + 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()) { - UserName = email, - Email = email, - DisplayName = "Super Admin", - CreatedAt = DateTimeOffset.UtcNow, - }; - var result = await userManager.CreateAsync(account, password); - if (result.Succeeded) - await userManager.AddToRoleAsync(account, "SuperAdmin"); + var r = role.GetString(); + if (r is not null) + identity.AddClaim(new Claim(ClaimTypes.Role, r)); + } } + catch { /* malformed access token — ignore */ } } diff --git a/Server/src/SOR.Admin/SOR.Admin.csproj b/Server/src/SOR.Admin/SOR.Admin.csproj index 06a04b7..f936b25 100644 --- a/Server/src/SOR.Admin/SOR.Admin.csproj +++ b/Server/src/SOR.Admin/SOR.Admin.csproj @@ -5,6 +5,8 @@ + + all diff --git a/Server/src/SOR.Admin/appsettings.json b/Server/src/SOR.Admin/appsettings.json index dd2ab87..2f25cf7 100644 --- a/Server/src/SOR.Admin/appsettings.json +++ b/Server/src/SOR.Admin/appsettings.json @@ -25,5 +25,17 @@ } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + // Keycloak OIDC — override in production via k8s secret env vars: + // Keycloak__Authority, Keycloak__ClientId, Keycloak__ClientSecret + // A confidential client "sor-admin" must be created in the Keycloak realm with: + // - Valid redirect URI: https:///signin-oidc + // - Post-logout URI: https:///signout-callback-oidc + // - "admin" realm role assigned to any user who should access this panel + "Keycloak": { + "Authority": "https://auth.aeternalisgames.com/realms/aeternalis", + "ClientId": "sor-admin", + "ClientSecret": "" + } }