Replace SOR.Admin email/password login with Keycloak OIDC
Admin panel now delegates authentication entirely to Keycloak using the
Authorization Code flow. The local Identity password form and
IdentityRevalidatingAuthenticationStateProvider are removed. Access requires
the "admin" Keycloak realm role, mirroring the game's role-based auth model.
- Program.cs: AddOpenIdConnect("Keycloak") with cookie session; /auth/challenge
triggers the OIDC flow; /auth/logout signs out of both cookie and Keycloak SSO
- Login.razor: replaced HTML form with an immediate redirect to /auth/challenge
- IdentityRevalidatingAuthenticationStateProvider.cs: deleted (no longer needed)
- appsettings.json: Keycloak:Authority / ClientId / ClientSecret section added
- Directory.Packages.props: pinned Microsoft.AspNetCore.Authentication.OpenIdConnect 8.0.0
- SOR.Admin.csproj: added OpenIdConnect package reference
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>
This commit is contained in:
@@ -18,6 +18,7 @@
|
||||
<PackageVersion Include="Grpc.Net.ClientFactory" Version="2.62.0" />
|
||||
<!-- ── NATS ───────────────────────────────────────────────────────────── -->
|
||||
<!-- Official NATS .NET client (NATS.Net is the modern unified package) -->
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.0" />
|
||||
<PackageVersion Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.0.0" />
|
||||
<PackageVersion Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="8.0.0" />
|
||||
<PackageVersion Include="NATS.Net" Version="2.3.0" />
|
||||
|
||||
@@ -1,45 +1,14 @@
|
||||
@page "/login"
|
||||
@attribute [AllowAnonymous]
|
||||
@* Static SSR — no rendermode, keeps login available without a SignalR connection. *@
|
||||
@inject NavigationManager Nav
|
||||
|
||||
<PageTitle>Sign In – SOR Admin</PageTitle>
|
||||
|
||||
<div class="min-vh-100 d-flex align-items-center justify-content-center bg-dark">
|
||||
<div class="card shadow" style="width: 380px;">
|
||||
<div class="card-body p-4">
|
||||
<h1 class="h4 mb-1 fw-bold">
|
||||
<i class="bi bi-lightning-charge-fill text-warning me-2"></i>SOR Admin
|
||||
</h1>
|
||||
<p class="text-muted small mb-4">Sign in to continue</p>
|
||||
|
||||
@if (Error == "invalid")
|
||||
{
|
||||
<div class="alert alert-danger py-2">Invalid email or password.</div>
|
||||
}
|
||||
else if (Error == "locked")
|
||||
{
|
||||
<div class="alert alert-warning py-2">Account locked — try again later.</div>
|
||||
}
|
||||
|
||||
<form method="post" action="/auth/login">
|
||||
<input type="hidden" name="returnUrl" value="@ReturnUrl" />
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Email</label>
|
||||
<input name="email" type="email" class="form-control"
|
||||
placeholder="admin@example.com" required autofocus />
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label class="form-label">Password</label>
|
||||
<input name="password" type="password" class="form-control" required />
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary w-100">Sign In</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@* Static SSR — no rendermode, stays available without a SignalR connection. *@
|
||||
|
||||
@code {
|
||||
[SupplyParameterFromQuery] public string? ReturnUrl { get; set; }
|
||||
[SupplyParameterFromQuery] public string? Error { get; set; }
|
||||
|
||||
protected override void OnInitialized() =>
|
||||
Nav.NavigateTo(
|
||||
$"/auth/challenge?returnUrl={Uri.EscapeDataString(ReturnUrl ?? "/")}",
|
||||
forceLoad: true);
|
||||
}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
namespace SOR.Admin;
|
||||
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SOR.Database.Entities.Identity;
|
||||
|
||||
/// <summary>
|
||||
/// Revalidates the Identity cookie on a schedule while a Blazor Server circuit
|
||||
/// is open, so that bans or role changes take effect without a page reload.
|
||||
/// This is the standard pattern from the Blazor Identity scaffolding.
|
||||
/// </summary>
|
||||
internal sealed class IdentityRevalidatingAuthenticationStateProvider(
|
||||
ILoggerFactory loggerFactory,
|
||||
IServiceScopeFactory scopeFactory,
|
||||
IOptions<IdentityOptions> options)
|
||||
: RevalidatingServerAuthenticationStateProvider(loggerFactory)
|
||||
{
|
||||
protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(30);
|
||||
|
||||
protected override async Task<bool> ValidateAuthenticationStateAsync(
|
||||
AuthenticationState authenticationState,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using var scope = scopeFactory.CreateAsyncScope();
|
||||
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<Account>>();
|
||||
return await ValidateSecurityStampAsync(userManager, authenticationState.User);
|
||||
}
|
||||
|
||||
private async Task<bool> ValidateSecurityStampAsync(
|
||||
UserManager<Account> userManager,
|
||||
System.Security.Claims.ClaimsPrincipal principal)
|
||||
{
|
||||
var user = await userManager.GetUserAsync(principal);
|
||||
if (user is null) return false;
|
||||
if (!userManager.SupportsUserSecurityStamp) return true;
|
||||
|
||||
var principalStamp = principal
|
||||
.FindFirst(options.Value.ClaimsIdentity.SecurityStampClaimType)?.Value;
|
||||
var userStamp = await userManager.GetSecurityStampAsync(user);
|
||||
return principalStamp == userStamp;
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,19 @@
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using StackExchange.Redis;
|
||||
using SOR.Admin;
|
||||
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);
|
||||
|
||||
@@ -25,36 +28,68 @@ builder.Services.AddSignalR(opts =>
|
||||
|
||||
// Required for <AuthorizeView> and [Authorize] in Blazor components.
|
||||
builder.Services.AddCascadingAuthenticationState();
|
||||
builder.Services.AddScoped<AuthenticationStateProvider,
|
||||
IdentityRevalidatingAuthenticationStateProvider>();
|
||||
|
||||
// ── Identity + Cookie Auth ──────────────────────────────────────────────────
|
||||
builder.Services.AddAuthentication(options =>
|
||||
// ── 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 = IdentityConstants.ApplicationScheme;
|
||||
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
|
||||
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||
options.DefaultChallengeScheme = "Keycloak";
|
||||
})
|
||||
.AddIdentityCookies();
|
||||
.AddCookie(options =>
|
||||
{
|
||||
// Redirect to the challenge shim instead of a password form.
|
||||
options.LoginPath = "/auth/challenge";
|
||||
options.SlidingExpiration = true;
|
||||
options.ExpireTimeSpan = TimeSpan.FromHours(8);
|
||||
})
|
||||
.AddOpenIdConnect("Keycloak", options =>
|
||||
{
|
||||
options.Authority = builder.Configuration["Keycloak:Authority"];
|
||||
options.ClientId = builder.Configuration["Keycloak:ClientId"];
|
||||
options.ClientSecret = builder.Configuration["Keycloak:ClientSecret"];
|
||||
options.ResponseType = "code";
|
||||
options.SaveTokens = true;
|
||||
// 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
|
||||
{
|
||||
OnTokenValidated = ctx =>
|
||||
{
|
||||
// Extract Keycloak realm roles from the access token and add them as
|
||||
// ClaimTypes.Role so that [Authorize(Roles = "admin")] works normally.
|
||||
if (ctx.Principal?.Identity is ClaimsIdentity identity
|
||||
&& ctx.TokenEndpointResponse?.AccessToken is { Length: > 0 } accessToken)
|
||||
{
|
||||
AddRealmRoleClaims(identity, accessToken);
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// Redirect to /login instead of the default /Account/Login.
|
||||
builder.Services.ConfigureApplicationCookie(options =>
|
||||
{
|
||||
options.LoginPath = "/login";
|
||||
options.AccessDeniedPath = "/login";
|
||||
options.SlidingExpiration = true;
|
||||
options.ExpireTimeSpan = TimeSpan.FromHours(8);
|
||||
});
|
||||
|
||||
// All Blazor pages require Admin or SuperAdmin role by default.
|
||||
// Override per-page with [AllowAnonymous] (login page only).
|
||||
// All Blazor pages require the "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("Admin", "SuperAdmin")
|
||||
.RequireRole("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;
|
||||
@@ -66,11 +101,9 @@ builder.Services.AddIdentityCore<Account>(options =>
|
||||
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
|
||||
})
|
||||
.AddRoles<IdentityRole<Guid>>()
|
||||
.AddEntityFrameworkStores<SorIdentityDbContext>()
|
||||
.AddSignInManager()
|
||||
.AddDefaultTokenProviders();
|
||||
.AddEntityFrameworkStores<SorIdentityDbContext>();
|
||||
|
||||
// ── Razor Pages (used for login/logout form posts) ─────────────────────────
|
||||
// ── Razor Pages ────────────────────────────────────────────────────────────
|
||||
builder.Services.AddRazorPages();
|
||||
|
||||
// ── Redis ──────────────────────────────────────────────────────────────────
|
||||
@@ -110,36 +143,21 @@ app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.UseAntiforgery();
|
||||
|
||||
// ── Auth endpoints (form POST targets — cookies cannot be set from Blazor) ──
|
||||
// ── Auth endpoints ─────────────────────────────────────────────────────────
|
||||
|
||||
// Login: called by the /login page form.
|
||||
app.MapPost("/auth/login", async (
|
||||
HttpContext ctx,
|
||||
[FromForm] string email,
|
||||
[FromForm] string password,
|
||||
[FromForm] string? returnUrl,
|
||||
UserManager<Account> userManager,
|
||||
SignInManager<Account> signInManager) =>
|
||||
// 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) =>
|
||||
{
|
||||
var user = await userManager.FindByEmailAsync(email);
|
||||
if (user is not null)
|
||||
{
|
||||
var result = await signInManager.PasswordSignInAsync(
|
||||
user, password, isPersistent: false, lockoutOnFailure: true);
|
||||
if (result.Succeeded)
|
||||
return Results.LocalRedirect(
|
||||
string.IsNullOrWhiteSpace(returnUrl) ? "/" : returnUrl);
|
||||
if (result.IsLockedOut)
|
||||
return Results.Redirect("/login?error=locked");
|
||||
}
|
||||
return Results.Redirect("/login?error=invalid");
|
||||
}).AllowAnonymous().DisableAntiforgery();
|
||||
await ctx.ChallengeAsync("Keycloak",
|
||||
new AuthenticationProperties { RedirectUri = returnUrl ?? "/" });
|
||||
}).AllowAnonymous();
|
||||
|
||||
// Logout: called by the nav menu form.
|
||||
app.MapPost("/auth/logout", async (SignInManager<Account> signInManager) =>
|
||||
// Logout: signs out of the local cookie AND the Keycloak SSO session.
|
||||
app.MapPost("/auth/logout", async (HttpContext ctx) =>
|
||||
{
|
||||
await signInManager.SignOutAsync();
|
||||
return Results.Redirect("/login");
|
||||
await ctx.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
await ctx.SignOutAsync("Keycloak");
|
||||
}).DisableAntiforgery();
|
||||
|
||||
// ── Blazor + Razor Pages ──────────────────────────────────────────────────
|
||||
@@ -150,11 +168,10 @@ app.MapRazorComponents<App>()
|
||||
// ── Apply pending migrations ───────────────────────────────────────────────
|
||||
await MigrateAllAsync(app);
|
||||
|
||||
// ── Seed roles and initial SuperAdmin ─────────────────────────────────────
|
||||
await SeedAsync(app);
|
||||
|
||||
app.Run();
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
static async Task MigrateAllAsync(WebApplication app)
|
||||
{
|
||||
using var scope = app.Services.CreateScope();
|
||||
@@ -168,35 +185,29 @@ static async Task MigrateAllAsync(WebApplication app)
|
||||
await sp.GetRequiredService<SupportDbContext>().Database.MigrateAsync();
|
||||
}
|
||||
|
||||
static async Task SeedAsync(WebApplication app)
|
||||
/// <summary>
|
||||
/// Decodes the Keycloak access token (already validated by OIDC middleware) and
|
||||
/// adds realm_access.roles entries as <see cref="ClaimTypes.Role"/> claims so that
|
||||
/// [Authorize(Roles = "admin")] and <AuthorizeView Roles="admin"> work normally.
|
||||
/// </summary>
|
||||
static void AddRealmRoleClaims(ClaimsIdentity identity, string accessToken)
|
||||
{
|
||||
using var scope = app.Services.CreateScope();
|
||||
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole<Guid>>>();
|
||||
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<Account>>();
|
||||
var cfg = scope.ServiceProvider.GetRequiredService<IConfiguration>();
|
||||
|
||||
foreach (var role in new[] { "SuperAdmin", "Admin", "player", "moderator", "card_builder" })
|
||||
// JWT: header.payload.signature — payload is base64url encoded JSON.
|
||||
var parts = accessToken.Split('.');
|
||||
if (parts.Length != 3) return;
|
||||
try
|
||||
{
|
||||
if (!await roleManager.RoleExistsAsync(role))
|
||||
await roleManager.CreateAsync(new IdentityRole<Guid>(role));
|
||||
}
|
||||
|
||||
// Create the first SuperAdmin if none exists.
|
||||
// Override via appsettings / env vars: Admin:Email Admin:Password
|
||||
var email = cfg["Admin:Email"] ?? "admin@sor.local";
|
||||
var password = cfg["Admin:Password"] ?? "SOR!Admin#Forge$2026@AeternalisGames%Prod";
|
||||
|
||||
if (await userManager.FindByEmailAsync(email) is null)
|
||||
{
|
||||
var account = new Account
|
||||
var padding = (4 - parts[1].Length % 4) % 4;
|
||||
var base64 = parts[1].Replace('-', '+').Replace('_', '/') + new string('=', padding);
|
||||
using var doc = JsonDocument.Parse(Convert.FromBase64String(base64));
|
||||
if (!doc.RootElement.TryGetProperty("realm_access", out var realmAccess)) return;
|
||||
if (!realmAccess.TryGetProperty("roles", out var rolesEl)) return;
|
||||
foreach (var role in rolesEl.EnumerateArray())
|
||||
{
|
||||
UserName = email,
|
||||
Email = email,
|
||||
DisplayName = "Super Admin",
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
var result = await userManager.CreateAsync(account, password);
|
||||
if (result.Succeeded)
|
||||
await userManager.AddToRoleAsync(account, "SuperAdmin");
|
||||
var r = role.GetString();
|
||||
if (r is not null)
|
||||
identity.AddClaim(new Claim(ClaimTypes.Role, r));
|
||||
}
|
||||
}
|
||||
catch { /* malformed access token — ignore */ }
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" />
|
||||
|
||||
<!-- Design-time only: enables 'dotnet ef migrations add' targeting this project -->
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
|
||||
@@ -25,5 +25,17 @@
|
||||
}
|
||||
},
|
||||
|
||||
"AllowedHosts": "*"
|
||||
"AllowedHosts": "*",
|
||||
|
||||
// Keycloak OIDC — override in production via k8s secret env vars:
|
||||
// Keycloak__Authority, Keycloak__ClientId, Keycloak__ClientSecret
|
||||
// A confidential client "sor-admin" must be created in the Keycloak realm with:
|
||||
// - Valid redirect URI: https://<admin-host>/signin-oidc
|
||||
// - Post-logout URI: https://<admin-host>/signout-callback-oidc
|
||||
// - "admin" realm role assigned to any user who should access this panel
|
||||
"Keycloak": {
|
||||
"Authority": "https://auth.aeternalisgames.com/realms/aeternalis",
|
||||
"ClientId": "sor-admin",
|
||||
"ClientSecret": ""
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user