Files
sor/Server/src/SOR.Website/Program.cs
T
88695149d2 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>
2026-04-25 16:58:07 -04:00

284 lines
14 KiB
C#

// SOR.Website — Public game website for Origin: Stone of Revival
//
// 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.
//
// 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 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.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);
// ── Logging ───────────────────────────────────────────────────────────────────
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 ─────────────────────────────────────────────────────────────────────
var redisConnectionString = builder.Configuration.GetConnectionString("Redis") ?? "localhost:6379";
var redisConfig = ConfigurationOptions.Parse(redisConnectionString);
redisConfig.AbortOnConnectFail = false;
var redis = ConnectionMultiplexer.Connect(redisConfig);
builder.Services.AddSingleton<IConnectionMultiplexer>(redis);
// ── DataProtection ────────────────────────────────────────────────────────────
builder.Services.AddDataProtection()
.PersistKeysToStackExchangeRedis(redis, "SOR.Website:DataProtection-Keys")
.SetApplicationName("SOR.Website");
// ── Databases ─────────────────────────────────────────────────────────────────
builder.Services.AddIdentityDatabase(builder.Configuration);
builder.Services.AddCatalogDatabase(builder.Configuration);
builder.Services.AddGameDatabase(builder.Configuration);
// ── 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 =>
{
opts.SignIn.RequireConfirmedAccount = false;
})
.AddRoles<IdentityRole<Guid>>()
.AddEntityFrameworkStores<SorIdentityDbContext>();
// ── 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"];
// 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.ResponseType = "code";
opts.SaveTokens = true;
opts.GetClaimsFromUserInfoEndpoint = false; // token already contains all we need
opts.MapInboundClaims = false;
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 ──────────────────────────────────────────────────────────────
builder.Services.AddAntiforgery(opts =>
{
opts.Cookie.Name = "__Host-sor-csrf";
opts.Cookie.HttpOnly = true;
opts.Cookie.SecurePolicy = CookieSecurePolicy.Always;
opts.Cookie.SameSite = SameSiteMode.Strict;
opts.Cookie.Path = "/";
opts.HeaderName = "X-CSRF-TOKEN";
});
// ── Razor Pages ───────────────────────────────────────────────────────────────
builder.Services.AddRazorPages(opts =>
{
opts.Conventions.AuthorizeFolder("/Account");
});
// ── Forwarded headers ─────────────────────────────────────────────────────────
// 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 =
ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto |
ForwardedHeaders.XForwardedHost;
opts.KnownNetworks.Clear();
opts.KnownProxies.Clear();
});
// ── Health checks ─────────────────────────────────────────────────────────────
builder.Services.AddHealthChecks();
// ── BUILD ─────────────────────────────────────────────────────────────────────
var app = builder.Build();
app.UseForwardedHeaders();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler(err => err.Run(async ctx =>
{
ctx.Response.StatusCode = 500;
ctx.Response.ContentType = "text/html; charset=utf-8";
await ctx.Response.WriteAsync(
"<!DOCTYPE html><html><body><h1>An error occurred.</h1></body></html>");
}));
app.UseHsts();
}
app.UseMiddleware<SecurityHeadersMiddleware>();
app.UseStaticFiles();
app.UseRouting();
app.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();
app.MapHealthChecks("/health").AllowAnonymous();
// ── 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() { }
}