// 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(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 for profile lookups (display name, // rank score, etc.) without registering SignInManager or Identity cookie auth. builder.Services.AddIdentityCore(opts => { opts.SignIn.RequireConfirmedAccount = false; }) .AddRoles>() .AddEntityFrameworkStores(); // ── 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>(); 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(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( "

An error occurred.

"); })); app.UseHsts(); } app.UseMiddleware(); 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>() .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 { public Task GetConfigurationAsync(CancellationToken cancel) => Task.FromResult(config); public void RequestRefresh() { } }