Add Keycloak authentication via Authorization Code + PKCE

- auth.proto: add ExchangeKeycloakToken RPC + request/response messages
- KeycloakOptions: binds Keycloak:Authority + Keycloak:ClientId from config
- KeycloakTokenValidator: validates Keycloak JWTs via OIDC discovery/JWKS;
  extracts sub, email, preferred_username, realm_access.roles
- AuthGrpcHandler.ExchangeKeycloakToken:
  - validates JWT and requires "player" realm role
  - lazy-migrates existing accounts by email on first Keycloak login
  - creates new passwordless accounts from Keycloak claims
  - syncs preferred_username → DisplayName on every login
  - single-session policy: revokes prior sessions before issuing SOR token
- AuthGrpcHandler.Register: assign "player" role to all new registrations
- ServiceRegistration: wire KeycloakOptions + KeycloakTokenValidator as singleton
- Admin SeedAsync: seed player, moderator, card_builder roles alongside Admin/SuperAdmin
- IGatewayAuthValidator / GatewayAuthValidator: add ExchangeKeycloakTokenAsync
- ConnectionLoop: handle auth.keycloak message type → auth.keycloak.ack
- appsettings.json: add Keycloak section (Authority + ClientId, overridable via env)

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:
dingo
2026-04-02 14:27:32 -04:00
co-authored by Claude Happy
parent 78f55930a0
commit d5363fa014
12 changed files with 328 additions and 13 deletions
+3 -11
View File
@@ -5,28 +5,25 @@
This prevents version drift — if you need to upgrade a package, change it here only. -->
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<!-- ── Dependency Injection ──────────────────────────────────────────── -->
<!-- DI abstractions (IServiceCollection, IServiceProvider) for class library projects.
Web SDK projects (Microsoft.NET.Sdk.Web) get this transitively from the framework.
Pure class libraries need to reference it directly. -->
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
<!-- ── gRPC ────────────────────────────────────────────────────────────── -->
<!-- ASP.NET Core gRPC server + client + Protobuf code generation -->
<PackageVersion Include="Grpc.AspNetCore" Version="2.62.0" />
<!-- gRPC client factory — integrates with ASP.NET Core DI + HttpClientFactory -->
<PackageVersion Include="Grpc.Net.ClientFactory" Version="2.62.0" />
<!-- ── NATS ───────────────────────────────────────────────────────────── -->
<!-- Official NATS .NET client (NATS.Net is the modern unified package) -->
<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" />
<!-- ── Redis ─────────────────────────────────────────────────────────── -->
<!-- StackExchange.Redis: battle-tested, high-performance Redis client for .NET -->
<PackageVersion Include="StackExchange.Redis" Version="2.7.33" />
<!-- ── Entity Framework Core ─────────────────────────────────────────── -->
<!-- EF Core ORM: maps C# classes to database tables, generates SQL queries -->
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
@@ -36,11 +33,9 @@
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0" />
<!-- Identity with EF Core: user/role store backed by a DbContext -->
<PackageVersion Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0" />
<!-- ── AWS SDK ────────────────────────────────────────────────────────── -->
<!-- S3-compatible object storage client (also works with Ceph RadosGW) -->
<PackageVersion Include="AWSSDK.S3" Version="3.7.414.0" />
<!-- ── Logging ────────────────────────────────────────────────────────── -->
<!-- Serilog: structured logging library (replaces Microsoft's default logger) -->
<PackageVersion Include="Serilog.AspNetCore" Version="8.0.0" />
@@ -48,16 +43,13 @@
<PackageVersion Include="Serilog.Sinks.Console" Version="5.0.0" />
<!-- Seq sink: sends logs to a Seq log server for querying and alerting -->
<PackageVersion Include="Serilog.Sinks.Seq" Version="7.0.0" />
<!-- ── Serialization ─────────────────────────────────────────────────── -->
<!-- MessagePack: binary serialization, faster + smaller than JSON.
Registered as an alternative IMessageSerializer when performance matters. -->
<PackageVersion Include="MessagePack" Version="2.5.140" />
<!-- ── Health Checks ─────────────────────────────────────────────────── -->
<!-- Redis health check for Kubernetes liveness/readiness probes -->
<PackageVersion Include="AspNetCore.HealthChecks.Redis" Version="8.0.1" />
<!-- ── Testing ───────────────────────────────────────────────────────── -->
<!-- xUnit: the test framework (test discovery, runner, assertions) -->
<PackageVersion Include="xunit" Version="2.6.6" />
@@ -72,4 +64,4 @@
<!-- In-process test server for integration tests -->
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.0" />
</ItemGroup>
</Project>
</Project>
+1 -1
View File
@@ -175,7 +175,7 @@ static async Task SeedAsync(WebApplication app)
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<Account>>();
var cfg = scope.ServiceProvider.GetRequiredService<IConfiguration>();
foreach (var role in new[] { "SuperAdmin", "Admin" })
foreach (var role in new[] { "SuperAdmin", "Admin", "player", "moderator", "card_builder" })
{
if (!await roleManager.RoleExistsAsync(role))
await roleManager.CreateAsync(new IdentityRole<Guid>(role));
@@ -34,17 +34,20 @@ public sealed class AuthGrpcHandler : AuthService.AuthServiceBase
private readonly UserManager<Account> _userManager;
private readonly SorIdentityDbContext _db;
private readonly IConnectionMultiplexer _redis;
private readonly KeycloakTokenValidator _keycloak;
private readonly ILogger<AuthGrpcHandler> _logger;
public AuthGrpcHandler(
UserManager<Account> userManager,
SorIdentityDbContext db,
IConnectionMultiplexer redis,
KeycloakTokenValidator keycloak,
ILogger<AuthGrpcHandler> logger)
{
_userManager = userManager;
_db = db;
_redis = redis;
_keycloak = keycloak;
_logger = logger;
}
@@ -116,6 +119,8 @@ public sealed class AuthGrpcHandler : AuthService.AuthServiceBase
return Fail<RegisterResponse>(r => { r.ErrorCode = code; return r; });
}
await _userManager.AddToRoleAsync(account, "player");
var token = await CreateSessionAsync(account.Id, context);
_logger.LogInformation("Registered new account {AccountId}", account.Id);
return new RegisterResponse
@@ -325,6 +330,94 @@ public sealed class AuthGrpcHandler : AuthService.AuthServiceBase
return response;
}
// ── Keycloak Exchange ─────────────────────────────────────────────────────
public override async Task<ExchangeKeycloakTokenResponse> ExchangeKeycloakToken(
ExchangeKeycloakTokenRequest request, ServerCallContext context)
{
// 1. Validate the Keycloak JWT — checks signature, issuer, audience, expiry.
var claims = await _keycloak.ValidateAsync(request.KeycloakToken, context.CancellationToken);
if (!claims.Valid)
return Fail<ExchangeKeycloakTokenResponse>(r => { r.ErrorCode = "INVALID_TOKEN"; return r; });
// 2. Require the "player" realm role.
if (!claims.RealmRoles.Contains("player"))
{
_logger.LogWarning(
"Keycloak exchange rejected — sub={Sub} lacks player role (roles: {Roles})",
claims.Sub, string.Join(",", claims.RealmRoles));
return Fail<ExchangeKeycloakTokenResponse>(r => { r.ErrorCode = "ROLE_REQUIRED"; return r; });
}
// 3. Find existing account by Keycloak sub (stored as external login).
var account = await _userManager.FindByLoginAsync("keycloak", claims.Sub);
if (account is null)
{
// 4a. Lazy migration: if an account with the same email exists, link it.
account = await _userManager.FindByEmailAsync(claims.Email);
if (account is not null)
{
await _userManager.AddLoginAsync(account,
new UserLoginInfo("keycloak", claims.Sub, "Keycloak"));
_logger.LogInformation(
"Lazy-migrated existing account {AccountId} to Keycloak sub {Sub}",
account.Id, claims.Sub);
}
else
{
// 4b. Brand-new account — create it from Keycloak claims.
account = new Account
{
UserName = claims.Email,
Email = claims.Email,
DisplayName = claims.PreferredUsername,
CreatedAt = DateTimeOffset.UtcNow,
LastLoginAt = DateTimeOffset.UtcNow,
};
// No password — this account authenticates exclusively via Keycloak.
var createResult = await _userManager.CreateAsync(account);
if (!createResult.Succeeded)
{
_logger.LogWarning(
"Failed to create account for Keycloak sub {Sub}: {Errors}",
claims.Sub, string.Join(", ", createResult.Errors.Select(e => e.Code)));
return Fail<ExchangeKeycloakTokenResponse>(r => { r.ErrorCode = "ACCOUNT_CREATION_FAILED"; return r; });
}
await _userManager.AddToRoleAsync(account, "player");
await _userManager.AddLoginAsync(account,
new UserLoginInfo("keycloak", claims.Sub, "Keycloak"));
_logger.LogInformation(
"Created new account {AccountId} for Keycloak sub {Sub}", account.Id, claims.Sub);
}
}
// 5. Sync display name from Keycloak preferred_username on every login.
if (account.DisplayName != claims.PreferredUsername && !string.IsNullOrEmpty(claims.PreferredUsername))
{
account.DisplayName = claims.PreferredUsername;
await _userManager.UpdateAsync(account);
}
account.LastLoginAt = DateTimeOffset.UtcNow;
await _userManager.UpdateAsync(account);
// 6. Single-session policy — revoke all prior sessions, then issue a new one.
await RevokeAllSessionsForUserAsync(account.Id);
var token = await CreateSessionAsync(account.Id, context);
return new ExchangeKeycloakTokenResponse
{
Success = true,
SessionToken = token,
NeedsStarterDeck = !account.StarterDeckSelectedAt.HasValue,
};
}
// ── OAuth (disabled — feature-flagged) ────────────────────────────────────
public override async Task<OAuthLoginResponse> LoginWithOAuth(
+24
View File
@@ -0,0 +1,24 @@
namespace SOR.Auth;
/// <summary>
/// Bound from the "Keycloak" section of appsettings.
///
/// "Keycloak": {
/// "Authority": "https://auth.aeternalisgames.com/realms/aeternalis",
/// "ClientId": "sor-game"
/// }
///
/// Authority is the Keycloak realm URL — used as the JWT issuer and as the base
/// for OIDC discovery (Authority/.well-known/openid-configuration).
/// ClientId must match the "aud" claim in the access token.
/// </summary>
public sealed class KeycloakOptions
{
public const string Section = "Keycloak";
/// <summary>Keycloak realm URL, e.g. https://auth.aeternalisgames.com/realms/aeternalis</summary>
public string Authority { get; set; } = string.Empty;
/// <summary>Keycloak client ID configured for the game, e.g. sor-game</summary>
public string ClientId { get; set; } = string.Empty;
}
@@ -0,0 +1,117 @@
namespace SOR.Auth;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
/// <summary>
/// Validates Keycloak access tokens against the aeternalis realm's JWKS endpoint.
///
/// Registered as a Singleton — <see cref="ConfigurationManager{T}"/> caches the OIDC
/// metadata and signing keys in memory, refreshing them automatically when keys rotate.
///
/// Usage: inject and call <see cref="ValidateAsync"/> before trusting any claims.
/// </summary>
public sealed class KeycloakTokenValidator
{
private readonly ConfigurationManager<OpenIdConnectConfiguration> _configManager;
private readonly TokenValidationParameters _baseParams;
private readonly ILogger<KeycloakTokenValidator> _logger;
public KeycloakTokenValidator(
IOptions<KeycloakOptions> options,
ILogger<KeycloakTokenValidator> logger)
{
_logger = logger;
var opts = options.Value;
_configManager = new ConfigurationManager<OpenIdConnectConfiguration>(
$"{opts.Authority}/.well-known/openid-configuration",
new OpenIdConnectConfigurationRetriever(),
new HttpDocumentRetriever { RequireHttps = opts.Authority.StartsWith("https://", StringComparison.OrdinalIgnoreCase) });
_baseParams = new TokenValidationParameters
{
ValidIssuer = opts.Authority,
ValidAudience = opts.ClientId,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
// Clock skew: allow 30 s to account for minor time drift between servers.
ClockSkew = TimeSpan.FromSeconds(30),
};
}
/// <summary>
/// Validates a Keycloak access token and extracts the claims we need.
///
/// Returns <c>Valid = false</c> for any validation failure (expired, bad sig, wrong issuer, etc.).
/// <c>RealmRoles</c> is the list from <c>realm_access.roles</c> in the JWT payload.
/// </summary>
public async Task<KeycloakClaimsResult> ValidateAsync(
string token, CancellationToken ct = default)
{
try
{
var oidcConfig = await _configManager.GetConfigurationAsync(ct);
var vp = _baseParams.Clone();
vp.IssuerSigningKeys = oidcConfig.SigningKeys;
var handler = new JsonWebTokenHandler();
var result = await handler.ValidateTokenAsync(token, vp);
if (!result.IsValid)
{
_logger.LogDebug("Keycloak JWT validation failed: {Reason}", result.Exception?.Message);
return KeycloakClaimsResult.Invalid;
}
var jwt = (JsonWebToken)result.SecurityToken;
result.Claims.TryGetValue("sub", out var subObj);
result.Claims.TryGetValue("email", out var emailObj);
result.Claims.TryGetValue("preferred_username", out var usernameObj);
var sub = subObj?.ToString() ?? string.Empty;
var email = emailObj?.ToString() ?? string.Empty;
var username = usernameObj?.ToString() ?? string.Empty;
// realm_access is a JSON object in the payload: { "roles": ["player", ...] }
var roles = new List<string>();
if (jwt.TryGetPayloadValue("realm_access", out JsonElement realmAccess)
&& realmAccess.TryGetProperty("roles", out var rolesArr))
{
foreach (var r in rolesArr.EnumerateArray())
{
var s = r.GetString();
if (s is not null) roles.Add(s);
}
}
return new KeycloakClaimsResult(true, sub, email, username, roles);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Unexpected error validating Keycloak token");
return KeycloakClaimsResult.Invalid;
}
}
}
/// <summary>Extracted claims from a validated Keycloak JWT.</summary>
public sealed record KeycloakClaimsResult(
bool Valid,
string Sub,
string Email,
string PreferredUsername,
IReadOnlyList<string> RealmRoles)
{
public static readonly KeycloakClaimsResult Invalid =
new(false, string.Empty, string.Empty, string.Empty, Array.Empty<string>());
}
+4
View File
@@ -7,6 +7,10 @@
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Grpc.AspNetCore" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" />
<PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" />
<!-- IConnectionMultiplexer for Redis-backed session store (fast token validation) -->
<PackageReference Include="StackExchange.Redis" />
@@ -6,6 +6,7 @@ using Microsoft.Extensions.DependencyInjection;
using SOR.Database;
using SOR.Database.Contexts;
using SOR.Database.Entities.Identity;
using SOR.Auth;
/// <summary>
/// Registers all Auth service dependencies in the DI container.
@@ -42,6 +43,11 @@ public static class ServiceRegistration
.AddEntityFrameworkStores<SorIdentityDbContext>()
.AddDefaultTokenProviders();
// Keycloak JWT validation — binds "Keycloak" config section, registers
// KeycloakTokenValidator as a singleton (OIDC config manager caches signing keys).
services.Configure<KeycloakOptions>(configuration.GetSection(KeycloakOptions.Section));
services.AddSingleton<KeycloakTokenValidator>();
return services;
}
}
@@ -101,4 +101,27 @@ public sealed class GatewayAuthValidator : IGatewayAuthValidator
return (false, "AUTH_SERVICE_UNAVAILABLE", string.Empty, string.Empty, string.Empty, false);
}
}
/// <inheritdoc/>
public async Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName, bool NeedsStarterDeck)>
ExchangeKeycloakTokenAsync(string keycloakToken, CancellationToken cancellationToken = default)
{
try
{
var response = await _grpcClient.ExchangeKeycloakTokenAsync(
new ExchangeKeycloakTokenRequest { KeycloakToken = keycloakToken },
cancellationToken: cancellationToken);
if (!response.Success)
return (false, response.ErrorCode, string.Empty, string.Empty, string.Empty, false);
var validate = await ValidateAsync(response.SessionToken, cancellationToken);
return (true, string.Empty, response.SessionToken, validate.UserId, validate.DisplayName, validate.NeedsStarterDeck);
}
catch (Grpc.Core.RpcException ex)
{
_logger.LogWarning(ex, "Auth gRPC call failed during Keycloak exchange: {Status}", ex.Status.StatusCode);
return (false, "AUTH_SERVICE_UNAVAILABLE", string.Empty, string.Empty, string.Empty, false);
}
}
}
@@ -34,4 +34,12 @@ public interface IGatewayAuthValidator
/// </summary>
Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName, bool NeedsStarterDeck)>
RegisterAsync(string email, string password, string displayName, CancellationToken cancellationToken = default);
/// <summary>
/// Exchanges a Keycloak access token for a SOR session token.
/// The Auth service validates the JWT, finds or creates the account, and issues a session.
/// ErrorCode is set on failure (INVALID_TOKEN | ROLE_REQUIRED | ACCOUNT_CREATION_FAILED).
/// </summary>
Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName, bool NeedsStarterDeck)>
ExchangeKeycloakTokenAsync(string keycloakToken, CancellationToken cancellationToken = default);
}
+20 -1
View File
@@ -164,12 +164,30 @@ public sealed class ConnectionLoop
break;
}
case "auth.keycloak":
{
AuthKeycloakPayload payload;
try { payload = _serializer.DeserializePayload<AuthKeycloakPayload>(parsedMsg.Payload); }
catch { await RejectAsync(rawConnection, parsedMsg.Seq, "INVALID_PAYLOAD", "auth.keycloak payload is malformed.", appCancellationToken); return; }
var (success, errorCode, token, uid, dname, nsd) =
await _authValidator.ExchangeKeycloakTokenAsync(payload.KeycloakToken, appCancellationToken);
if (!success)
{
await RejectAsync(rawConnection, parsedMsg.Seq, errorCode, "Keycloak token exchange failed.", appCancellationToken);
return;
}
(sessionToken, userId, displayName, ackType, needsStarterDeck) =
(token, uid, dname, "auth.keycloak.ack", nsd);
break;
}
default:
_logger.LogWarning(
"First message is not an auth type: Type={Type} ConnectionId={ConnectionId}",
parsedMsg.Type, rawConnection.ConnectionId);
await RejectAsync(rawConnection, parsedMsg.Seq, "AUTH_REQUIRED",
"First message must be auth.hello, auth.login, or auth.register.",
"First message must be auth.hello, auth.login, auth.register, or auth.keycloak.",
appCancellationToken);
return;
}
@@ -324,4 +342,5 @@ public sealed class ConnectionLoop
private sealed record AuthHelloPayload(string SessionToken);
private sealed record AuthLoginPayload(string Email, string Password);
private sealed record AuthRegisterPayload(string Email, string Password, string DisplayName);
private sealed record AuthKeycloakPayload(string KeycloakToken);
}
+8
View File
@@ -28,6 +28,14 @@
"Services": {
"Auth": "http://localhost:5001"
},
"Keycloak": {
// Realm base URL — also used as the JWT issuer claim.
// Production: override via env var Keycloak__Authority
"Authority": "https://auth.aeternalisgames.com/realms/aeternalis",
// Must match the Keycloak client ID configured for the game.
// Production: override via env var Keycloak__ClientId
"ClientId": "sor-game"
},
"Serilog": {
"MinimumLevel": {
"Default": "Information",
@@ -120,6 +120,24 @@ message ListAccountPropertiesResponse {
repeated AccountPropertyEntry properties = 1;
}
// ── Keycloak Exchange ─────────────────────────────────────────────────────────
// Client obtains a Keycloak access token (Authorization Code + PKCE against the
// aeternalis realm), then sends it here to receive a SOR session token.
// The JWT is validated against the realm's JWKS endpoint.
// On first exchange the account is created (or lazy-migrated by email match).
message ExchangeKeycloakTokenRequest {
string keycloak_token = 1;
}
message ExchangeKeycloakTokenResponse {
bool success = 1;
string session_token = 2;
// Failure codes: INVALID_TOKEN | ROLE_REQUIRED | ACCOUNT_CREATION_FAILED
string error_code = 3;
bool needs_starter_deck = 4;
}
// ── OAuth ─────────────────────────────────────────────────────────────────────
// All providers are DISABLED by default, gated by Redis feature flags:
// oauth_google_enabled | oauth_steam_enabled | oauth_apple_enabled | oauth_microsoft_enabled
@@ -173,4 +191,7 @@ service AuthService {
// OAuth login — disabled until provider credentials are configured and Redis flag is set.
rpc LoginWithOAuth(OAuthLoginRequest) returns (OAuthLoginResponse);
// Exchange a Keycloak access token for a SOR session token.
rpc ExchangeKeycloakToken(ExchangeKeycloakTokenRequest) returns (ExchangeKeycloakTokenResponse);
}