feat(website): Keycloak SSO auth, leaderboard tabs, HowToPlay CMS, webclient redirect

- SOR.Website now uses Keycloak OIDC (same realm as webclient) for SSO;
  clicking Play no longer re-prompts for login
- /webclient redirects directly to webclient.aeternalisgames.com (no auth gate)
- Leaderboard: 4 ranked tabs — Rank Score, Games Played, Games Won, Win Rate
  (Win Rate requires min 10 games; active column highlighted)
- HowToPlay page reads body HTML from catalog.website_contents (key=howtoplay);
  falls back to built-in static content when no DB entry exists
- Admin: HowToPlayEditor at /website/how-to-play with live HTML preview + clear
- Admin NavMenu: How To Play link added under Website section
- WebsiteContent entity + EF migration (catalog schema)
- appsettings.json: added Keycloak config skeleton (values from k8s secrets)
- Index page: branding corrected to "Origin: Stone of Revival" / Aeternalis Games;
  hero image sourced from CDN

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:
dingo
2026-04-25 16:58:07 -04:00
co-authored by Claude Happy
parent f58a976745
commit 88695149d2
18 changed files with 1228 additions and 275 deletions
+180 -165
View File
@@ -1,29 +1,36 @@
// SOR.Website — Public game website and player account portal
// SOR.Website — Public game website for Origin: Stone of Revival
//
// This is the entry point for aeternalisgames.com. It runs independently of
// SOR.Host and connects to the same databases (Identity, Catalog) so player
// accounts created here work immediately in the game client.
// Authentication is delegated entirely to Keycloak (same realm as the game client).
// This gives the player a single SSO session: logging in on the website means
// clicking "Play" opens the webclient without a second auth prompt.
//
// Security design:
// - All HTML rendered by Razor Pages is HTML-encoded by default (XSS impossible).
// - Content-Security-Policy blocks all inline scripts/styles (SecurityHeadersMiddleware).
// - Anti-forgery tokens are validated on every POST handler (Razor Pages default).
// - Auth cookie uses __Host- prefix: forces Secure, Path=/, and no Domain attribute.
// - Data Protection keys stored in Redis: all pods decrypt each other's cookies.
// - Rate limiting applied per-IP to all auth endpoints.
// - Forwarded-header trust enables accurate IP tracking behind the ingress.
// Auth flow:
// 1. Unauthenticated request → cookie middleware redirects to /auth/challenge
// 2. /auth/challenge initiates Keycloak OIDC code flow
// 3. Keycloak callback → OnTicketReceived finds/creates local Account by email
// and adds display_name claim to the cookie
// 4. Local cookie session set — user is signed in on the website
// 5. User clicks Play → https://webclient.aeternalisgames.com
// Keycloak recognises the existing SSO session → no second login prompt
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Serilog;
using StackExchange.Redis;
using SOR.Database;
using SOR.Database.Contexts;
using SOR.Database.Entities.Identity;
using SOR.Website;
using System.Security.Claims;
var builder = WebApplication.CreateBuilder(args);
@@ -31,8 +38,13 @@ var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((ctx, cfg) =>
cfg.ReadFrom.Configuration(ctx.Configuration));
// ── Keycloak config (fail fast) ───────────────────────────────────────────────
var keycloakAuthority = builder.Configuration["Keycloak:Authority"]
?? throw new InvalidOperationException("Keycloak:Authority is required.");
var keycloakClientId = builder.Configuration["Keycloak:ClientId"]
?? throw new InvalidOperationException("Keycloak:ClientId is required.");
// ── Redis ─────────────────────────────────────────────────────────────────────
// Create the Redis connection eagerly so DataProtection can share it.
var redisConnectionString = builder.Configuration.GetConnectionString("Redis") ?? "localhost:6379";
var redisConfig = ConfigurationOptions.Parse(redisConnectionString);
redisConfig.AbortOnConnectFail = false;
@@ -40,81 +52,120 @@ var redis = ConnectionMultiplexer.Connect(redisConfig);
builder.Services.AddSingleton<IConnectionMultiplexer>(redis);
// ── DataProtection ────────────────────────────────────────────────────────────
// Persist keys in Redis so all pod replicas can decrypt each other's session cookies.
// SetApplicationName ensures cookie protection is scoped to this app — different apps
// sharing the same Redis instance cannot accidentally decrypt each other's cookies.
builder.Services.AddDataProtection()
.PersistKeysToStackExchangeRedis(redis, "SOR.Website:DataProtection-Keys")
.SetApplicationName("SOR.Website");
// ── Identity databases ────────────────────────────────────────────────────────
// ── Databases ─────────────────────────────────────────────────────────────────
builder.Services.AddIdentityDatabase(builder.Configuration);
builder.Services.AddCatalogDatabase(builder.Configuration);
builder.Services.AddGameDatabase(builder.Configuration);
// ── ASP.NET Core Identity ─────────────────────────────────────────────────────
// Registers UserManager<Account>, SignInManager<Account>, and all token providers.
// Password rules and lockout here MUST match SOR.Auth/ServiceRegistration.cs so that
// passwords set via the website are accepted by the game client and vice versa.
builder.Services.AddIdentity<Account, IdentityRole<Guid>>(options =>
// ── Identity (UserManager only — sign-in is Keycloak's job) ──────────────────
// AddIdentityCore gives us UserManager<Account> for profile lookups (display name,
// rank score, etc.) without registering SignInManager or Identity cookie auth.
builder.Services.AddIdentityCore<Account>(opts =>
{
// Password policy (must match SOR.Auth)
options.Password.RequireDigit = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequiredLength = 8;
// Account lockout after 5 failed attempts
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.AllowedForNewUsers = true;
// Email is the unique login identifier
options.User.RequireUniqueEmail = true;
// Email verification is advisory for now (players can play before verifying).
// Set RequireConfirmedEmail = true when an email provider is configured.
options.SignIn.RequireConfirmedEmail = false;
opts.SignIn.RequireConfirmedAccount = false;
})
.AddEntityFrameworkStores<SorIdentityDbContext>()
.AddDefaultTokenProviders();
.AddRoles<IdentityRole<Guid>>()
.AddEntityFrameworkStores<SorIdentityDbContext>();
// ── Cookie configuration ──────────────────────────────────────────────────────
// AddIdentity registers the application cookie automatically.
// ConfigureApplicationCookie overrides the defaults to apply maximum security.
//
// __Host- prefix requirements (enforced by the browser, not us):
// - The Secure attribute must be set.
// - The Path attribute must be "/".
// - The Domain attribute must NOT be set.
// Together these prevent the cookie from being set by a subdomain compromise
// and ensure it is never sent over plain HTTP even if a redirect occurs.
builder.Services.ConfigureApplicationCookie(opts =>
{
opts.Cookie.Name = "__Host-sor-web-session";
opts.Cookie.HttpOnly = true; // inaccessible to JavaScript — blocks XSS token theft
opts.Cookie.SecurePolicy = CookieSecurePolicy.Always; // never sent over HTTP
opts.Cookie.SameSite = SameSiteMode.Strict; // never sent on cross-site requests
opts.Cookie.Path = "/"; // required for __Host- prefix
// ── Keycloak OIDC authentication ──────────────────────────────────────────────
builder.Services
.AddAuthentication(opts =>
{
opts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opts.DefaultChallengeScheme = "Keycloak";
})
.AddCookie(opts =>
{
// Unauthenticated requests to /Account/* are redirected here.
// /auth/challenge immediately triggers the Keycloak OIDC flow.
opts.LoginPath = "/auth/challenge";
opts.Cookie.Name = "__Host-sor-web-session";
opts.Cookie.HttpOnly = true;
opts.Cookie.SecurePolicy = CookieSecurePolicy.Always;
opts.Cookie.SameSite = SameSiteMode.Lax; // Lax required: OIDC callback is a cross-site POST
opts.Cookie.Path = "/";
opts.SlidingExpiration = true;
opts.ExpireTimeSpan = TimeSpan.FromDays(14);
})
.AddOpenIdConnect("Keycloak", opts =>
{
opts.Authority = keycloakAuthority;
opts.ClientId = keycloakClientId;
opts.ClientSecret = builder.Configuration["Keycloak:ClientSecret"];
opts.LoginPath = "/auth/login";
opts.LogoutPath = "/auth/logout";
opts.AccessDeniedPath = "/auth/login"; // unauthorized → login, not 403 page
opts.ReturnUrlParameter = "returnUrl"; // param name in /auth/login?returnUrl=...
// If the public Keycloak URL isn't reachable from inside the cluster (DNS /
// network policy), point MetadataAddress at the internal k8s service URL.
// Authority is still used for issuer validation in token claims.
var meta = builder.Configuration["Keycloak:MetadataAddress"];
if (!string.IsNullOrEmpty(meta))
{
opts.MetadataAddress = meta;
opts.RequireHttpsMetadata = false;
}
opts.SlidingExpiration = true;
opts.ExpireTimeSpan = TimeSpan.FromDays(14);
opts.ResponseType = "code";
opts.SaveTokens = true;
opts.GetClaimsFromUserInfoEndpoint = false; // token already contains all we need
opts.MapInboundClaims = false;
// SecurityStampValidator re-checks the stamp every 30 minutes by default.
// This means password changes and bans take effect within that window
// without a full DB hit on every single request.
});
opts.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "preferred_username",
ValidateAudience = false,
};
opts.Events = new OpenIdConnectEvents
{
OnTicketReceived = async ctx =>
{
if (ctx.Principal?.Identity is not ClaimsIdentity identity) return;
// ── Extract identity from the Keycloak access token ──────────
var accessToken = ctx.Properties?.GetTokenValue("access_token");
string? email = identity.FindFirst("email")?.Value;
string? preferredUsername = identity.FindFirst("preferred_username")?.Value;
string? displayName = identity.FindFirst("name")?.Value
?? preferredUsername;
// ── Find or provision the local Account record ───────────────
// Account records are keyed by email (same email the player uses
// in Keycloak). If this is their first website login, a stub account
// is created so pages that query identity (leaderboard, profile) work.
if (!string.IsNullOrEmpty(email))
{
var userManager = ctx.HttpContext.RequestServices
.GetRequiredService<UserManager<Account>>();
var account = await userManager.FindByEmailAsync(email);
if (account is null)
{
account = new Account
{
UserName = email,
Email = email,
DisplayName = displayName?.Trim() ?? email,
CreatedAt = DateTimeOffset.UtcNow,
RankScore = 1000,
};
await userManager.CreateAsync(account);
}
// Use the stored DisplayName (player may have changed it in-game).
displayName = account.DisplayName ?? displayName ?? email;
}
// ── Add display_name claim so nav bar renders without a DB hit ──
if (!string.IsNullOrEmpty(displayName))
identity.AddClaim(new Claim("display_name", displayName));
},
};
});
// ── Anti-forgery ──────────────────────────────────────────────────────────────
// Razor Pages validates anti-forgery tokens on every POST handler by default.
// We apply the same strict cookie security as the session cookie.
// The HeaderName allows JavaScript fetch requests to send the token via header
// rather than form body (needed for AJAX calls with JSON bodies).
builder.Services.AddAntiforgery(opts =>
{
opts.Cookie.Name = "__Host-sor-csrf";
@@ -126,68 +177,14 @@ builder.Services.AddAntiforgery(opts =>
});
// ── Razor Pages ───────────────────────────────────────────────────────────────
// AuthorizeFolder("/Account") applies [Authorize] to every page under /Account.
// No individual page needs the attribute — it is enforced at the routing layer.
// This is the privilege-escalation control: unauthenticated requests to any
// /Account/* page are automatically redirected to /auth/login?returnUrl=...
builder.Services.AddRazorPages(opts =>
{
opts.Conventions.AuthorizeFolder("/Account");
});
// ── Rate limiting ─────────────────────────────────────────────────────────────
// Applied per-IP address to auth endpoints to slow brute-force attacks.
// IP is obtained from the RemoteIpAddress, which reflects the real client IP
// because UseForwardedHeaders() is applied early in the pipeline below.
//
// Policies are applied via [EnableRateLimiting("policy-name")] on page models.
builder.Services.AddRateLimiter(opts =>
{
opts.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
// Login: 10 attempts per IP per 5 minutes
opts.AddPolicy("auth-login", httpCtx =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: httpCtx.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 10,
Window = TimeSpan.FromMinutes(5),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0,
}));
// Registration: 5 per IP per hour
opts.AddPolicy("auth-register", httpCtx =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: httpCtx.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromHours(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0,
}));
// Password reset: 3 per IP per 15 minutes
opts.AddPolicy("auth-reset", httpCtx =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: httpCtx.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 3,
Window = TimeSpan.FromMinutes(15),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0,
}));
});
// ── Forwarded headers ─────────────────────────────────────────────────────────
// The pod runs plain HTTP behind a TLS-terminating ingress (nginx/Traefik/etc.).
// Without this, ASP.NET Core sees the ingress IP as the client, breaking rate
// limiting (all clients appear to share one IP) and HSTS redirect logic.
// Clearing KnownNetworks/KnownProxies trusts any upstream proxy — safe because
// the pod is only reachable from within the cluster network.
// Pod runs plain HTTP behind TLS-terminating ingress. Without this the OIDC
// middleware builds the redirect_uri as "http://..." which Keycloak rejects.
builder.Services.Configure<ForwardedHeadersOptions>(opts =>
{
opts.ForwardedHeaders =
@@ -202,20 +199,12 @@ builder.Services.Configure<ForwardedHeadersOptions>(opts =>
builder.Services.AddHealthChecks();
// ── BUILD ─────────────────────────────────────────────────────────────────────
var app = builder.Build();
// ── Middleware pipeline ───────────────────────────────────────────────────────
// Order is critical. Each line's comment explains why it must be at this position.
// 1. Forwarded headers: must be first so all subsequent middleware sees the
// real client IP, scheme, and host from proxy headers.
app.UseForwardedHeaders();
if (!app.Environment.IsDevelopment())
{
// 2a. Exception handler in production: inline so it never redirects to a
// protected route that would trigger an auth challenge loop.
app.UseExceptionHandler(err => err.Run(async ctx =>
{
ctx.Response.StatusCode = 500;
@@ -223,46 +212,72 @@ if (!app.Environment.IsDevelopment())
await ctx.Response.WriteAsync(
"<!DOCTYPE html><html><body><h1>An error occurred.</h1></body></html>");
}));
// 2b. HSTS: instructs browsers to always use HTTPS for this domain.
// The ingress terminates TLS; the pod itself is plain HTTP.
// UseHttpsRedirection is intentionally omitted — the pod never receives
// HTTPS directly, so redirecting would cause an infinite loop.
app.UseHsts();
}
// 3. Security headers: must come before static files so every response (including
// CSS, JS, images) carries the full security header set.
app.UseMiddleware<SecurityHeadersMiddleware>();
// 4. Static files: serves wwwroot/ content.
// Comes before routing so requests for .css/.js/.png etc. short-circuit here
// without hitting the Razor Pages routing layer.
app.UseStaticFiles();
// 5. Routing: maps URL paths to page handlers.
app.UseRouting();
// 6. Rate limiting: must come after UseRouting (needs endpoint metadata) and
// before UseAuthentication (so we can reject before doing any DB work).
app.UseRateLimiter();
// 7. Authentication: reads the __Host-sor-web-session cookie and populates
// HttpContext.User with the signed-in Account's claims.
app.UseAuthentication();
// 8. Authorization: enforces [Authorize] and AuthorizeFolder conventions.
// Must come after UseAuthentication.
app.UseAuthorization();
// ── Auth endpoints ────────────────────────────────────────────────────────────
// Challenge: triggers the Keycloak OIDC flow. The cookie middleware redirects
// here automatically when a request is unauthenticated.
app.MapGet("/auth/challenge", async (HttpContext ctx,
[Microsoft.AspNetCore.Mvc.FromQuery] string? returnUrl) =>
{
await ctx.ChallengeAsync("Keycloak",
new AuthenticationProperties { RedirectUri = returnUrl ?? "/" });
}).AllowAnonymous();
// Logout: signs out of the local cookie AND the Keycloak SSO session so the
// player must re-authenticate on both the website and the webclient.
app.MapPost("/auth/logout", async (HttpContext ctx) =>
{
await ctx.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await ctx.SignOutAsync("Keycloak",
new AuthenticationProperties { RedirectUri = "/" });
}).AllowAnonymous();
// ── Endpoints ─────────────────────────────────────────────────────────────────
app.MapRazorPages();
// Health check: AllowAnonymous so Kubernetes probes work before any session exists.
app.MapHealthChecks("/health").AllowAnonymous();
// ── RUN ───────────────────────────────────────────────────────────────────────
// ── Eager OIDC discovery ──────────────────────────────────────────────────────
await CheckOidcDiscoveryAsync(app);
Log.Information("SOR.Website starting");
await app.RunAsync();
// ── Helpers ───────────────────────────────────────────────────────────────────
static async Task CheckOidcDiscoveryAsync(WebApplication app)
{
var opts = app.Services
.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<OpenIdConnectOptions>>()
.Get("Keycloak");
var url = opts.MetadataAddress ?? $"{opts.Authority}/.well-known/openid-configuration";
try
{
var config = await opts.ConfigurationManager!.GetConfigurationAsync(CancellationToken.None);
opts.ConfigurationManager = new FixedConfigurationManager(config);
app.Logger.LogInformation("Keycloak OIDC discovery OK: {AuthEndpoint}", config.AuthorizationEndpoint);
}
catch (Exception ex)
{
app.Logger.LogError(ex,
"Keycloak OIDC discovery FAILED from {Url}. " +
"Set Keycloak__MetadataAddress to the internal k8s service URL if the " +
"public auth domain is not reachable from the pod.", url);
}
}
sealed class FixedConfigurationManager(OpenIdConnectConfiguration config)
: IConfigurationManager<OpenIdConnectConfiguration>
{
public Task<OpenIdConnectConfiguration> GetConfigurationAsync(CancellationToken cancel)
=> Task.FromResult(config);
public void RequestRefresh() { }
}