From 26d7d8381106b5f253f7cd90ebf65f499789e2dd Mon Sep 17 00:00:00 2001 From: WorkClub Automation Date: Fri, 20 Mar 2026 10:42:31 +0100 Subject: [PATCH] Fix middleware order - place Authentication before TenantValidation The JWT middleware needs to fetch signing keys from Keycloak before tenant validation runs. The previous order caused signature validation to fail because the middleware was blocking the JWKS endpoint requests. - Moved Authentication before TenantValidationMiddleware - Removed realm endpoint from exemption list (not needed with correct order) - This allows JWT middleware to fetch signing keys and validate tokens --- .../WorkClub.Api/Middleware/TenantValidationMiddleware.cs | 5 +++-- backend/WorkClub.Api/Program.cs | 5 ++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/backend/WorkClub.Api/Middleware/TenantValidationMiddleware.cs b/backend/WorkClub.Api/Middleware/TenantValidationMiddleware.cs index 3a90ccb..849dd8f 100644 --- a/backend/WorkClub.Api/Middleware/TenantValidationMiddleware.cs +++ b/backend/WorkClub.Api/Middleware/TenantValidationMiddleware.cs @@ -22,10 +22,11 @@ public class TenantValidationMiddleware return; } - // Exempt bootstrap, admin, and debug endpoints from tenant validation + // Exempt bootstrap, admin, debug, and Keycloak OIDC endpoints from tenant validation if (context.Request.Path.StartsWithSegments("/api/clubs/me") || context.Request.Path.StartsWithSegments("/api/admin") || - context.Request.Path.StartsWithSegments("/api/debug")) + context.Request.Path.StartsWithSegments("/api/debug") || + context.Request.Path.StartsWithSegments("/realms")) { _logger.LogInformation("TenantValidationMiddleware: Exempting {Path} from tenant validation", context.Request.Path); await _next(context); diff --git a/backend/WorkClub.Api/Program.cs b/backend/WorkClub.Api/Program.cs index 4754f71..1cbe477 100644 --- a/backend/WorkClub.Api/Program.cs +++ b/backend/WorkClub.Api/Program.cs @@ -147,9 +147,12 @@ app.UseHttpsRedirection(); app.UseCors("AllowFrontend"); +// IMPORTANT: Order matters! +// 1. Authentication must come before tenant validation so JWT middleware can fetch JWKS +// 2. Tenant validation should come after auth but before endpoints app.UseAuthentication(); -app.UseAuthorization(); app.UseMiddleware(); +app.UseAuthorization(); app.UseMiddleware(); app.MapHealthChecks("/health/live", new Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions