- Validate Keycloak:Authority and Keycloak:ClientId at startup with a clear InvalidOperationException. Previously a missing env var produced the cryptic "Cannot redirect to the authorization endpoint" error on every request. - Remove app.UseHttpsRedirection(). The pod runs plain HTTP on :8080; TLS is terminated at the ingress. The middleware had no HTTPS port to redirect to, generating a warning on every request and potentially interfering with the OIDC flow. 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>
255 lines
12 KiB
C#
255 lines
12 KiB
C#
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.HttpOverrides;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.IdentityModel.JsonWebTokens;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using StackExchange.Redis;
|
|
using SOR.Admin.Components;
|
|
using SOR.Cdn;
|
|
using SOR.Database;
|
|
using SOR.Database.Contexts;
|
|
using SOR.Database.Entities.Identity;
|
|
using System.Security.Claims;
|
|
using System.Text.Json;
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
|
|
// Fail fast with a clear message if Keycloak config is absent — prevents the
|
|
// cryptic "Cannot redirect to authorization endpoint" runtime error.
|
|
var keycloakAuthority = builder.Configuration["Keycloak:Authority"]
|
|
?? throw new InvalidOperationException("Keycloak:Authority is required. Set via Keycloak__Authority env var.");
|
|
var keycloakClientId = builder.Configuration["Keycloak:ClientId"]
|
|
?? throw new InvalidOperationException("Keycloak:ClientId is required. Set via Keycloak__ClientId env var.");
|
|
|
|
// ── Blazor Server ──────────────────────────────────────────────────────────
|
|
builder.Services.AddRazorComponents()
|
|
.AddInteractiveServerComponents();
|
|
|
|
// Increase SignalR hub message size to support large file uploads (art, 3D models).
|
|
// IBrowserFile.OpenReadStream streams through the SignalR hub in Blazor Server.
|
|
builder.Services.AddSignalR(opts =>
|
|
opts.MaximumReceiveMessageSize = 100 * 1024 * 1024); // 100 MB
|
|
|
|
// Required for <AuthorizeView> and [Authorize] in Blazor components.
|
|
builder.Services.AddCascadingAuthenticationState();
|
|
|
|
// ── Keycloak OIDC ──────────────────────────────────────────────────────────
|
|
// Authentication: cookie for the local session, Keycloak OIDC for the challenge.
|
|
// Override Keycloak:ClientSecret via env var (k8s secret): Keycloak__ClientSecret
|
|
builder.Services
|
|
.AddAuthentication(options =>
|
|
{
|
|
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
|
options.DefaultChallengeScheme = "Keycloak";
|
|
})
|
|
.AddCookie(options =>
|
|
{
|
|
options.LoginPath = "/auth/challenge";
|
|
// Explicit empty path: return 403 directly instead of redirecting to the
|
|
// default /Account/AccessDenied (which doesn't exist and causes a loop).
|
|
options.AccessDeniedPath = PathString.Empty;
|
|
options.SlidingExpiration = true;
|
|
options.ExpireTimeSpan = TimeSpan.FromHours(8);
|
|
})
|
|
.AddOpenIdConnect("Keycloak", options =>
|
|
{
|
|
options.Authority = keycloakAuthority;
|
|
options.ClientId = keycloakClientId;
|
|
options.ClientSecret = builder.Configuration["Keycloak:ClientSecret"];
|
|
options.ResponseType = "code";
|
|
options.SaveTokens = true;
|
|
// Don't call the UserInfo endpoint — that extra pod→Keycloak HTTPS hop
|
|
// was throwing and landing on /Error, which is itself protected and caused
|
|
// the 20-redirect loop. The access token already contains realm_access.roles.
|
|
options.GetClaimsFromUserInfoEndpoint = false;
|
|
// Don't map inbound claims — Keycloak uses non-standard claim names.
|
|
options.MapInboundClaims = false;
|
|
options.TokenValidationParameters = new TokenValidationParameters
|
|
{
|
|
NameClaimType = "preferred_username",
|
|
// Keycloak doesn't include the client ID in `aud` by default ("account" is used).
|
|
// Issuer + signature + realm roles is sufficient for single-realm deployment.
|
|
ValidateAudience = false,
|
|
};
|
|
options.Events = new OpenIdConnectEvents
|
|
{
|
|
// OnTicketReceived fires after SaveTokens, so the access token is
|
|
// guaranteed to be in ctx.Properties. Use JsonWebTokenHandler to decode
|
|
// it (no re-validation needed — OIDC middleware already validated it).
|
|
OnTicketReceived = ctx =>
|
|
{
|
|
if (ctx.Principal?.Identity is not ClaimsIdentity identity) return Task.CompletedTask;
|
|
var accessToken = ctx.Properties?.GetTokenValue("access_token");
|
|
if (string.IsNullOrEmpty(accessToken)) return Task.CompletedTask;
|
|
AddKeycloakRoleClaims(identity, accessToken);
|
|
return Task.CompletedTask;
|
|
},
|
|
};
|
|
});
|
|
|
|
// All Blazor pages require the "sor-admin" Keycloak realm role by default.
|
|
// Override per-page with [AllowAnonymous] (e.g. the login/challenge shim).
|
|
builder.Services.AddAuthorization(options =>
|
|
{
|
|
options.FallbackPolicy = new AuthorizationPolicyBuilder()
|
|
.RequireAuthenticatedUser()
|
|
.RequireRole("sor-admin")
|
|
.Build();
|
|
});
|
|
|
|
// Keep UserManager available for account-management pages in the admin panel.
|
|
// Sign-in machinery (SignInManager, token providers) is no longer needed —
|
|
// authentication is delegated entirely to Keycloak.
|
|
builder.Services.AddIdentityCore<Account>(options =>
|
|
{
|
|
options.SignIn.RequireConfirmedAccount = false;
|
|
options.Password.RequireDigit = true;
|
|
options.Password.RequireUppercase = true;
|
|
options.Password.RequireNonAlphanumeric = true;
|
|
options.Password.RequiredLength = 12;
|
|
options.Lockout.MaxFailedAccessAttempts = 5;
|
|
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
|
|
})
|
|
.AddRoles<IdentityRole<Guid>>()
|
|
.AddEntityFrameworkStores<SorIdentityDbContext>();
|
|
|
|
// ── Razor Pages ────────────────────────────────────────────────────────────
|
|
builder.Services.AddRazorPages();
|
|
|
|
// ── Redis ──────────────────────────────────────────────────────────────────
|
|
builder.Services.AddSingleton<IConnectionMultiplexer>(_ =>
|
|
{
|
|
var redisConnectionString = builder.Configuration.GetConnectionString("Redis") ?? "localhost:6379";
|
|
var redisOptions = ConfigurationOptions.Parse(redisConnectionString);
|
|
redisOptions.AbortOnConnectFail = false;
|
|
return ConnectionMultiplexer.Connect(redisOptions);
|
|
});
|
|
|
|
// ── CDN client ────────────────────────────────────────────────────────────
|
|
builder.Services.AddCdnClient(builder.Configuration);
|
|
|
|
// ── Databases ─────────────────────────────────────────────────────────────
|
|
builder.Services.AddIdentityDatabase(builder.Configuration);
|
|
builder.Services.AddCatalogDatabase(builder.Configuration);
|
|
builder.Services.AddCollectionDatabase(builder.Configuration);
|
|
builder.Services.AddBazaarDatabase(builder.Configuration);
|
|
builder.Services.AddChatDatabase(builder.Configuration);
|
|
builder.Services.AddGameDatabase(builder.Configuration);
|
|
builder.Services.AddSupportDatabase(builder.Configuration);
|
|
|
|
// ── Forwarded headers ─────────────────────────────────────────────────────
|
|
// The pod runs plain HTTP behind a TLS-terminating ingress. Without this,
|
|
// ASP.NET Core builds the OIDC redirect_uri as "http://..." which Keycloak
|
|
// rejects. Clearing KnownNetworks/KnownProxies trusts any upstream proxy —
|
|
// safe because the pod is only reachable from within the cluster.
|
|
builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
|
{
|
|
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
|
|
options.KnownNetworks.Clear();
|
|
options.KnownProxies.Clear();
|
|
});
|
|
|
|
// ── HTTP pipeline ─────────────────────────────────────────────────────────
|
|
var app = builder.Build();
|
|
|
|
// Must come before UseAuthentication so the scheme/host are correct when
|
|
// the OIDC middleware constructs the redirect_uri.
|
|
app.UseForwardedHeaders();
|
|
|
|
if (!app.Environment.IsDevelopment())
|
|
{
|
|
// Inline handler — avoids re-executing to a protected Blazor route (/Error),
|
|
// which would trigger an auth challenge and cause a redirect loop.
|
|
app.UseExceptionHandler(err => err.Run(async ctx =>
|
|
{
|
|
ctx.Response.StatusCode = 500;
|
|
ctx.Response.ContentType = "text/plain";
|
|
await ctx.Response.WriteAsync("An internal server error occurred.");
|
|
}));
|
|
// HSTS only — no UseHttpsRedirection. The pod runs plain HTTP; TLS is
|
|
// terminated at the ingress. Redirecting HTTP→HTTPS inside the pod would
|
|
// loop forever because the pod never receives HTTPS requests.
|
|
app.UseHsts();
|
|
}
|
|
app.UseStaticFiles();
|
|
app.UseRouting();
|
|
app.UseAuthentication();
|
|
app.UseAuthorization();
|
|
app.UseAntiforgery();
|
|
|
|
// ── Auth endpoints ─────────────────────────────────────────────────────────
|
|
|
|
// Challenge: cookie auth redirects here when a request is unauthenticated.
|
|
// Immediately initiates the Keycloak OIDC flow.
|
|
app.MapGet("/auth/challenge", async (HttpContext ctx, [FromQuery] string? returnUrl) =>
|
|
{
|
|
await ctx.ChallengeAsync("Keycloak",
|
|
new AuthenticationProperties { RedirectUri = returnUrl ?? "/" });
|
|
}).AllowAnonymous();
|
|
|
|
// Logout: signs out of the local cookie AND the Keycloak SSO session.
|
|
app.MapPost("/auth/logout", async (HttpContext ctx) =>
|
|
{
|
|
await ctx.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
|
await ctx.SignOutAsync("Keycloak");
|
|
}).DisableAntiforgery();
|
|
|
|
// ── Blazor + Razor Pages ──────────────────────────────────────────────────
|
|
app.MapRazorPages();
|
|
app.MapRazorComponents<App>()
|
|
.AddInteractiveServerRenderMode();
|
|
|
|
// ── Apply pending migrations ───────────────────────────────────────────────
|
|
await MigrateAllAsync(app);
|
|
|
|
app.Run();
|
|
|
|
// ── Helpers ────────────────────────────────────────────────────────────────
|
|
|
|
static async Task MigrateAllAsync(WebApplication app)
|
|
{
|
|
using var scope = app.Services.CreateScope();
|
|
var sp = scope.ServiceProvider;
|
|
await sp.GetRequiredService<SorIdentityDbContext>().Database.MigrateAsync();
|
|
await sp.GetRequiredService<CatalogDbContext>().Database.MigrateAsync();
|
|
await sp.GetRequiredService<CollectionDbContext>().Database.MigrateAsync();
|
|
await sp.GetRequiredService<BazaarDbContext>().Database.MigrateAsync();
|
|
await sp.GetRequiredService<ChatDbContext>().Database.MigrateAsync();
|
|
await sp.GetRequiredService<GameDbContext>().Database.MigrateAsync();
|
|
await sp.GetRequiredService<SupportDbContext>().Database.MigrateAsync();
|
|
}
|
|
|
|
// Decodes the Keycloak access token and adds realm_access.roles and groups
|
|
// as ClaimTypes.Role claims. Called from OnTicketReceived where SaveTokens
|
|
// has already run, so the token is guaranteed present in auth properties.
|
|
static void AddKeycloakRoleClaims(ClaimsIdentity identity, string accessToken)
|
|
{
|
|
var jwt = new JsonWebTokenHandler().ReadJsonWebToken(accessToken);
|
|
|
|
// Realm roles: realm_access.roles → ["sor-admin", ...]
|
|
if (jwt.TryGetPayloadValue("realm_access", out JsonElement realmAccess)
|
|
&& realmAccess.TryGetProperty("roles", out var realmRoles))
|
|
{
|
|
foreach (var role in realmRoles.EnumerateArray())
|
|
{
|
|
var r = role.GetString();
|
|
if (r is not null) identity.AddClaim(new Claim(ClaimTypes.Role, r));
|
|
}
|
|
}
|
|
|
|
// Group membership: groups → ["/sor-admin", ...] (leading slash stripped).
|
|
if (jwt.TryGetPayloadValue("groups", out JsonElement groups))
|
|
{
|
|
foreach (var group in groups.EnumerateArray())
|
|
{
|
|
var g = group.GetString()?.TrimStart('/');
|
|
if (!string.IsNullOrEmpty(g)) identity.AddClaim(new Claim(ClaimTypes.Role, g));
|
|
}
|
|
}
|
|
}
|