- /auth/challenge: validate returnUrl with IsLocalUrl before passing to
Keycloak redirect — blocks open-redirect phishing flows
- Dead local-auth pages (Login, Register, ForgotPassword, ResetPassword,
VerifyEmail) all injected SignInManager which is no longer registered;
replaced page models with simple redirects to /auth/challenge
- Stubbed their .cshtml views so the Razor compiler doesn't error on
missing model properties
- Added belt-and-suspenders MapGet guards in Program.cs for /auth/login,
/auth/register, /auth/forgot-password, /auth/reset-password
- Removed [EnableRateLimiting("auth-login")] dead attribute (Keycloak
handles brute-force; AddRateLimiter was never wired in this project)
Stored-HTML XSS (NewsPost / HowToPlay) is accepted by policy: content is
admin-only and the existing CSP (script-src 'self', no inline/eval) blocks
script injection.
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>
306 lines
15 KiB
C#
306 lines
15 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) =>
|
|
{
|
|
// Validate returnUrl is local before trusting it — prevents open-redirect abuse
|
|
// where an attacker crafts /auth/challenge?returnUrl=https://evil.com and the
|
|
// user gets bounced there after a legitimate Keycloak login.
|
|
var safeReturn = IsLocalUrl(returnUrl) ? returnUrl! : "/";
|
|
await ctx.ChallengeAsync("Keycloak",
|
|
new AuthenticationProperties { RedirectUri = safeReturn });
|
|
}).AllowAnonymous();
|
|
|
|
// Guard: old local-password auth routes no longer work (SignInManager is not registered).
|
|
// Redirect them to the Keycloak challenge so visitors get a working login flow instead of a 500.
|
|
app.MapGet("/auth/login", () => Results.Redirect("/auth/challenge")).AllowAnonymous();
|
|
app.MapGet("/auth/register", () => Results.Redirect("/auth/challenge")).AllowAnonymous();
|
|
app.MapGet("/auth/forgot-password",() => Results.Redirect("/auth/challenge")).AllowAnonymous();
|
|
app.MapGet("/auth/reset-password", () => Results.Redirect("/auth/challenge")).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 ───────────────────────────────────────────────────────────────────
|
|
|
|
// Mirrors ASP.NET Core's Url.IsLocalUrl logic.
|
|
// Rejects absolute URLs (https://evil.com), protocol-relative URLs (//evil.com),
|
|
// and backslash variants (/\evil.com) that some parsers treat as path separators.
|
|
static bool IsLocalUrl(string? url)
|
|
{
|
|
if (string.IsNullOrEmpty(url)) return false;
|
|
if (url[0] != '/') return false;
|
|
if (url.Length == 1) return true;
|
|
return url[1] != '/' && url[1] != (char)0x5C; // 0x5C = backslash
|
|
}
|
|
|
|
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() { }
|
|
}
|