+ }
diff --git a/Server/src/SOR.Website/Pages/HowToPlay.cshtml.cs b/Server/src/SOR.Website/Pages/HowToPlay.cshtml.cs
index bb2e681..18c00ec 100644
--- a/Server/src/SOR.Website/Pages/HowToPlay.cshtml.cs
+++ b/Server/src/SOR.Website/Pages/HowToPlay.cshtml.cs
@@ -1,8 +1,24 @@
namespace SOR.Website.Pages;
using Microsoft.AspNetCore.Mvc.RazorPages;
+using Microsoft.EntityFrameworkCore;
+using SOR.Database.Contexts;
-public sealed class HowToPlayModel : PageModel
+public sealed class HowToPlayModel(CatalogDbContext catalog) : PageModel
{
- public void OnGet() { }
+ ///
+ /// HTML body from the database. Null means no entry yet — the view falls
+ /// back to the static content embedded in HowToPlay.cshtml.
+ ///
+ public string? CustomBodyHtml { get; private set; }
+
+ public async Task OnGetAsync()
+ {
+ var entry = await catalog.WebsiteContents
+ .AsNoTracking()
+ .FirstOrDefaultAsync(w => w.Key == "howtoplay");
+
+ if (!string.IsNullOrWhiteSpace(entry?.BodyHtml))
+ CustomBodyHtml = entry.BodyHtml;
+ }
}
diff --git a/Server/src/SOR.Website/Pages/Index.cshtml b/Server/src/SOR.Website/Pages/Index.cshtml
index f310a42..0fbbfdc 100644
--- a/Server/src/SOR.Website/Pages/Index.cshtml
+++ b/Server/src/SOR.Website/Pages/Index.cshtml
@@ -2,8 +2,8 @@
@model IndexModel
@{
ViewData["Title"] = null; // Home page title is just "Aeternalis"
- ViewData["MetaDescription"] = "Channel the Archspirits. Shape the mindscape. Fill the void with stars. Aeternalis is a tactical strategy card game.";
- ViewData["OgTitle"] = "Aeternalis";
+ ViewData["MetaDescription"] = "Channel the Archspirits. Shape the mindscape. Fill the void with stars. Origin: Stone of Revival is a tactical strategy card game by Aeternalis Games.";
+ ViewData["OgTitle"] = "Origin: Stone of Revival";
ViewData["OgDescription"] = "Channel the Archspirits. Shape the mindscape. Fill the void with stars.";
}
@@ -18,7 +18,7 @@
loading="eager">
}
-
Aeternalis
+
Origin: Stone of Revival
Channel the Archspirits. Shape the mindscape. Fill the void with stars.
Play Now
diff --git a/Server/src/SOR.Website/Pages/Leaderboard.cshtml b/Server/src/SOR.Website/Pages/Leaderboard.cshtml
index 2fc3b36..c90fdae 100644
--- a/Server/src/SOR.Website/Pages/Leaderboard.cshtml
+++ b/Server/src/SOR.Website/Pages/Leaderboard.cshtml
@@ -2,7 +2,10 @@
@model LeaderboardModel
@{
ViewData["Title"] = "Leaderboard";
- ViewData["MetaDescription"] = "Top Channelers ranked by score. Who has filled the most stars?";
+ ViewData["MetaDescription"] = "Top Channelers in Origin: Stone of Revival — ranked by score, games played, wins, and win rate.";
+
+ string Tab(string name) => Model.ActiveTab == name ? "lb-tab lb-tab-active" : "lb-tab";
+ string Col(string tab) => Model.ActiveTab == tab ? "stat-cell stat-cell-active" : "stat-cell";
}
@@ -13,10 +16,27 @@
+
+
+
@if (!Model.Entries.Any())
{
-
No ranked games have been played yet. Be the first Channeler.
+
+ @if (Model.ActiveTab == "rate")
+ {
+ No players have completed 10 or more ranked games yet.
+ }
+ else
+ {
+ No ranked games have been played yet. Be the first Channeler.
+ }
+
@for (int i = 0; i < Model.Entries.Count; i++)
{
- var entry = Model.Entries[i];
- var rank = i + 1;
+ var entry = Model.Entries[i];
+ var rank = i + 1;
var isSelf = Model.CurrentUserDisplayName is not null
&& entry.DisplayName == Model.CurrentUserDisplayName;
@@ -47,19 +67,16 @@
{
@rank
}
- else
- {
- @rank
- }
+ else { @rank }
@entry.DisplayName
@if (isSelf) { (you) }
-
@entry.RankScore
-
@entry.GamesPlayed
-
@entry.GamesWon
-
@entry.WinRateDisplay
+
@entry.RankScore
+
@entry.GamesPlayed
+
@entry.GamesWon
+
@entry.WinRateDisplay
}
diff --git a/Server/src/SOR.Website/Pages/Leaderboard.cshtml.cs b/Server/src/SOR.Website/Pages/Leaderboard.cshtml.cs
index 41fdf6c..65154c6 100644
--- a/Server/src/SOR.Website/Pages/Leaderboard.cshtml.cs
+++ b/Server/src/SOR.Website/Pages/Leaderboard.cshtml.cs
@@ -5,46 +5,32 @@ using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Enums;
-///
-/// Public leaderboard showing top ranked players with win/loss stats.
-///
-/// Security controls:
-/// - Only exposes: DisplayName, RankScore, GamesPlayed, GamesWon.
-/// Never: Email, AccountId, or internal fields.
-/// - AI accounts and accounts hidden from leaderboard are excluded at query level.
-/// - Pagination limits response size.
-///
public sealed class LeaderboardModel(
SorIdentityDbContext identity,
GameDbContext game) : PageModel
{
public const int PageSize = 50;
+ public string ActiveTab { get; private set; } = "rank";
+
public IReadOnlyList Entries { get; private set; } = [];
public string? CurrentUserDisplayName { get; private set; }
- public async Task OnGetAsync()
+ public async Task OnGetAsync(string? by)
{
- // Step 1 — pull the top-ranked accounts (identity schema).
+ ActiveTab = by is "played" or "won" or "rate" ? by : "rank";
+
+ // Pull the top accounts from identity with all stats we might need.
var accounts = await identity.Users
.Where(a => !a.IsAi && !a.IsHiddenFromLeaderboard)
- .OrderByDescending(a => a.RankScore)
- .Take(PageSize)
.Select(a => new { a.Id, a.DisplayName, a.RankScore })
.AsNoTracking()
.ToListAsync();
- if (accounts.Count == 0)
- {
- Entries = [];
- return;
- }
+ if (accounts.Count == 0) return;
var accountIds = accounts.Select(a => a.Id).ToHashSet();
- // Step 2 — pull completed game sessions for those accounts (game schema).
- // A session counts for a player if they appear in any seat.
- // WinnerAccountId being in the set means they won that session.
var sessions = await game.GameSessions
.Where(s => s.Status == GameSessionStatus.Completed
&& (accountIds.Contains(s.PlayerOneAccountId)
@@ -58,7 +44,6 @@ public sealed class LeaderboardModel(
.AsNoTracking()
.ToListAsync();
- // Step 3 — aggregate wins and plays per account in memory.
var plays = new Dictionary();
var wins = new Dictionary();
@@ -67,32 +52,33 @@ public sealed class LeaderboardModel(
foreach (var id in new[] { s.PlayerOneAccountId, s.PlayerTwoAccountId }
.Where(accountIds.Contains))
{
- plays.TryGetValue(id, out var p);
- plays[id] = p + 1;
-
- if (s.WinnerAccountId == id)
- {
- wins.TryGetValue(id, out var w);
- wins[id] = w + 1;
- }
+ plays.TryGetValue(id, out var p); plays[id] = p + 1;
+ if (s.WinnerAccountId == id) { wins.TryGetValue(id, out var w); wins[id] = w + 1; }
}
}
- Entries = accounts
- .Select(a =>
+ var all = accounts.Select(a =>
+ {
+ var played = plays.GetValueOrDefault(a.Id);
+ var won = wins.GetValueOrDefault(a.Id);
+ return new LeaderboardEntry
{
- var played = plays.GetValueOrDefault(a.Id);
- var won = wins.GetValueOrDefault(a.Id);
- return new LeaderboardEntry
- {
- DisplayName = a.DisplayName ?? "Channeler",
- RankScore = a.RankScore,
- GamesPlayed = played,
- GamesWon = won,
- WinRate = played > 0 ? (double)won / played : 0,
- };
- })
- .ToList();
+ DisplayName = a.DisplayName ?? "Channeler",
+ RankScore = a.RankScore,
+ GamesPlayed = played,
+ GamesWon = won,
+ WinRate = played > 0 ? (double)won / played : 0,
+ };
+ });
+
+ Entries = ActiveTab switch
+ {
+ "played" => all.OrderByDescending(e => e.GamesPlayed).Take(PageSize).ToList(),
+ "won" => all.OrderByDescending(e => e.GamesWon).Take(PageSize).ToList(),
+ "rate" => all.Where(e => e.GamesPlayed >= 10)
+ .OrderByDescending(e => e.WinRate).Take(PageSize).ToList(),
+ _ => all.OrderByDescending(e => e.RankScore).Take(PageSize).ToList(),
+ };
if (User.Identity?.IsAuthenticated == true)
CurrentUserDisplayName = User.FindFirst("display_name")?.Value;
@@ -105,8 +91,6 @@ public sealed class LeaderboardModel(
public int GamesPlayed { get; init; }
public int GamesWon { get; init; }
public double WinRate { get; init; }
-
- public string WinRateDisplay =>
- GamesPlayed == 0 ? "—" : $"{WinRate:P0}";
+ public string WinRateDisplay => GamesPlayed == 0 ? "—" : $"{WinRate:P0}";
}
}
diff --git a/Server/src/SOR.Website/Pages/Shared/_Layout.cshtml b/Server/src/SOR.Website/Pages/Shared/_Layout.cshtml
index df47920..3b1c407 100644
--- a/Server/src/SOR.Website/Pages/Shared/_Layout.cshtml
+++ b/Server/src/SOR.Website/Pages/Shared/_Layout.cshtml
@@ -3,7 +3,7 @@
- @(ViewData["Title"] != null ? ViewData["Title"] + " — " : "")Aeternalis
+ @(ViewData["Title"] != null ? ViewData["Title"] + " — " : "")Origin: Stone of Revival
@if (ViewData["MetaDescription"] != null)
{
@@ -30,8 +30,8 @@
diff --git a/Server/src/SOR.Website/Pages/Webclient.cshtml.cs b/Server/src/SOR.Website/Pages/Webclient.cshtml.cs
index a9feb70..2905162 100644
--- a/Server/src/SOR.Website/Pages/Webclient.cshtml.cs
+++ b/Server/src/SOR.Website/Pages/Webclient.cshtml.cs
@@ -4,26 +4,14 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
///
-/// Canonical route for launching the game client.
-///
-/// Security controls:
-/// - Authenticated users are redirected directly (return URL preserved via cookie auth).
-/// - Unauthenticated users see a login gate — not an automatic redirect to the webclient
-/// URL, which prevents the webclient from being embedded without a session.
-/// - No dynamic content injected from query string into the page (no XSS surface).
+/// Passes the player directly to the game client.
+/// Auth is handled by Keycloak at the webclient level — if the player is already
+/// signed in on the website (same Keycloak realm), the webclient opens without
+/// a second login prompt (SSO).
///
public sealed class WebclientModel : PageModel
{
- // Hosted on its own subdomain so the game client can be updated independently.
public const string ClientUrl = "https://webclient.aeternalisgames.com";
- public bool IsAuthenticated => User.Identity?.IsAuthenticated == true;
-
- public IActionResult OnGet()
- {
- if (IsAuthenticated)
- return Redirect(ClientUrl);
-
- return Page();
- }
+ public IActionResult OnGet() => Redirect(ClientUrl);
}
diff --git a/Server/src/SOR.Website/Program.cs b/Server/src/SOR.Website/Program.cs
index ddfc878..5b14dfd 100644
--- a/Server/src/SOR.Website/Program.cs
+++ b/Server/src/SOR.Website/Program.cs
@@ -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(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, SignInManager, 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>(options =>
+// ── 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 =>
{
- // 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()
- .AddDefaultTokenProviders();
+ .AddRoles>()
+ .AddEntityFrameworkStores();
-// ── 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>();
+
+ 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(opts =>
{
opts.ForwardedHeaders =
@@ -202,20 +199,12 @@ builder.Services.Configure(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(
"
An error occurred.
");
}));
-
- // 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();
-
-// 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>()
+ .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() { }
+}
diff --git a/Server/src/SOR.Website/SOR.Website.csproj b/Server/src/SOR.Website/SOR.Website.csproj
index 5b08dcf..57ab37a 100644
--- a/Server/src/SOR.Website/SOR.Website.csproj
+++ b/Server/src/SOR.Website/SOR.Website.csproj
@@ -7,9 +7,14 @@
-
+
+
+
+
+
+
diff --git a/Server/src/SOR.Website/appsettings.json b/Server/src/SOR.Website/appsettings.json
index 0db8e12..371c50a 100644
--- a/Server/src/SOR.Website/appsettings.json
+++ b/Server/src/SOR.Website/appsettings.json
@@ -17,5 +17,10 @@
"Cdn": {
"PublicBaseUrl": "https://cdn.aeternalisgames.com"
},
+ "Keycloak": {
+ "Authority": "",
+ "ClientId": "",
+ "MetadataAddress": ""
+ },
"AllowedHosts": "*"
}