10 Commits

Author SHA1 Message Date
WorkClub Automation fdc1f415b7 Add test endpoint for middleware validation tests 2026-03-20 11:21:02 +01:00
WorkClub Automation 13f9e7be7f Fix JWT validation by configuring custom signing key resolver
- Added IssuerSigningKeyResolver to fetch JWKS directly from internal Keycloak URL
- This bypasses the localhost:8080 URLs in Keycloak's discovery document
- Ensures JWT tokens are validated against correct signing keys
2026-03-20 11:01:56 +01:00
WorkClub Automation 87c315c6fd Fix Keycloak hostname configuration for Docker internal communication
- Add MetadataAddress configuration to JWT middleware for internal Docker URLs
- Add KC_HOSTNAME_ADMIN and KC_SPI_HOSTNAME_DEFAULT_ADMIN to Keycloak env
- This ensures API can fetch JWKS from Keycloak via internal Docker network
- Tests passing: 63/63
2026-03-20 10:49:55 +01:00
WorkClub Automation 26d7d83811 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
2026-03-20 10:42:31 +01:00
WorkClub Automation 4ba76288b5 Add JWT debugging and fix Keycloak networking
- Added JWT authentication event logging to diagnose validation failures
- Fixed docker-compose networking for API to reach Keycloak via hostname
- Debug endpoint now accessible without auth for troubleshooting
- Still investigating why claims are not populated despite token being present
2026-03-20 10:30:10 +01:00
WorkClub Automation 97baf266a8 WIP: Fix Keycloak networking for API container 2026-03-20 10:15:50 +01:00
WorkClub Automation 0f9a7aba5c Make debug endpoint anonymous for troubleshooting 2026-03-20 09:56:24 +01:00
WorkClub Automation a3ca12da26 Add CORS configuration and exempt debug endpoint from tenant validation
- Add CORS policy to allow frontend requests from localhost:3000
- Exempt /api/debug endpoints from tenant validation
- Fix JSON parsing in realm_access claim checks
2026-03-20 09:42:16 +01:00
WorkClub Automation b52d75591b Add debug endpoint to inspect JWT claims 2026-03-20 09:34:29 +01:00
WorkClub Automation bb373a6b8e Fix admin authorization check - properly parse realm_access claim
The realm_access claim in JWT is a JSON object, not a simple string.
Previous string contains check was looking for escaped quotes in wrong format.

- Parse realm_access as JSON to extract roles array
- Check if 'admin' exists in roles array
- Fallback to string contains check if JSON parsing fails
- Applied fix in RequireGlobalAdmin policy, TenantValidationMiddleware,
  and ClubRoleClaimsTransformation

Fixes: Admin users getting 401 when trying to create clubs
2026-03-19 22:13:40 +01:00
4 changed files with 204 additions and 31 deletions
@@ -54,13 +54,36 @@ public class ClubRoleClaimsTransformation : IClaimsTransformation
return Task.FromResult(principal);
}
// --- NEW: Skip DB role lookup if user is a global admin ---
var realmAccess = principal.FindFirst("realm_access")?.Value;
if (!string.IsNullOrEmpty(realmAccess) && realmAccess.Contains("\"admin\"", StringComparison.OrdinalIgnoreCase))
// --- NEW: Skip DB role lookup if user is a global admin ---
var realmAccess = principal.FindFirst("realm_access")?.Value;
if (!string.IsNullOrEmpty(realmAccess) && IsAdminUser(realmAccess))
{
return Task.FromResult(principal);
}
// ---------------------------------------------------------
static bool IsAdminUser(string realmAccess)
{
try
{
using var doc = System.Text.Json.JsonDocument.Parse(realmAccess);
if (doc.RootElement.TryGetProperty("roles", out var rolesElement) &&
rolesElement.ValueKind == System.Text.Json.JsonValueKind.Array)
{
return Task.FromResult(principal);
foreach (var role in rolesElement.EnumerateArray())
{
if (role.GetString()?.Equals("admin", StringComparison.OrdinalIgnoreCase) == true)
return true;
}
}
// ---------------------------------------------------------
}
catch
{
// If JSON parsing fails, fallback to string contains check
return realmAccess.Contains("admin", StringComparison.OrdinalIgnoreCase);
}
return false;
}
// Look up the user's role in the database for the requested tenant
_httpContextAccessor.HttpContext!.Items["TenantId"] = tenantId;
@@ -22,14 +22,16 @@ public class TenantValidationMiddleware
return;
}
// Exempt bootstrap and admin endpoints from tenant validation
if (context.Request.Path.StartsWithSegments("/api/clubs/me") ||
context.Request.Path.StartsWithSegments("/api/admin"))
{
_logger.LogInformation("TenantValidationMiddleware: Exempting {Path} from tenant validation", context.Request.Path);
await _next(context);
return;
}
// 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("/realms"))
{
_logger.LogInformation("TenantValidationMiddleware: Exempting {Path} from tenant validation", context.Request.Path);
await _next(context);
return;
}
if (!context.Request.Headers.TryGetValue("X-Tenant-Id", out var tenantIdHeader) ||
string.IsNullOrWhiteSpace(tenantIdHeader))
@@ -44,13 +46,36 @@ public class TenantValidationMiddleware
if (string.IsNullOrEmpty(clubsClaim))
{
// NEW: Skip check if user is a global admin
var realmAccess = context.User.FindFirst("realm_access")?.Value;
if (!string.IsNullOrEmpty(realmAccess) && realmAccess.Contains("\"admin\"", StringComparison.OrdinalIgnoreCase))
{
await _next(context);
return;
}
// NEW: Skip check if user is a global admin
var realmAccess = context.User.FindFirst("realm_access")?.Value;
if (!string.IsNullOrEmpty(realmAccess) && IsAdminUser(realmAccess))
{
await _next(context);
return;
}
static bool IsAdminUser(string realmAccess)
{
try
{
using var doc = System.Text.Json.JsonDocument.Parse(realmAccess);
if (doc.RootElement.TryGetProperty("roles", out var rolesElement) &&
rolesElement.ValueKind == System.Text.Json.JsonValueKind.Array)
{
foreach (var role in rolesElement.EnumerateArray())
{
if (role.GetString()?.Equals("admin", StringComparison.OrdinalIgnoreCase) == true)
return true;
}
}
}
catch
{
// If JSON parsing fails, fallback to string contains check
return realmAccess.Contains("admin", StringComparison.OrdinalIgnoreCase);
}
return false;
}
context.Response.StatusCode = StatusCodes.Status403Forbidden;
await context.Response.WriteAsJsonAsync(new { error = "User does not have clubs claim" });
+130 -7
View File
@@ -31,6 +31,18 @@ builder.Services.AddScoped<MemberSyncService>();
builder.Services.AddScoped<TenantDbTransactionInterceptor>();
builder.Services.AddSingleton<SaveChangesTenantInterceptor>();
// Add CORS to allow frontend requests
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowFrontend", policy =>
{
policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
@@ -38,12 +50,75 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
options.Audience = builder.Configuration["Keycloak:Audience"];
options.RequireHttpsMetadata = false;
options.MapInboundClaims = false;
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
// For Docker internal communication, configure metadata and signing key resolution
// to bypass the hostname mismatch in Keycloak's discovery endpoint
var keycloakAuthority = builder.Configuration["Keycloak:Authority"];
var keycloakInternalUrl = "http://keycloak:8081";
if (keycloakAuthority?.Contains("keycloak:") == true)
{
ValidateIssuer = false, // Disabled for local dev - external clients use localhost:8080, internal use keycloak:8080
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true
// Set metadata address to internal Keycloak URL
options.MetadataAddress = $"{keycloakAuthority}/.well-known/openid-configuration";
// Configure custom signing key resolver to fetch from internal Keycloak URL
// This overrides the URLs returned in the discovery document
var httpClient = new HttpClient();
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKeyResolver = (token, securityToken, kid, validationParameters) =>
{
// Fetch JWKS from internal Keycloak URL
var jwksUrl = $"{keycloakInternalUrl}/realms/workclub/protocol/openid-connect/certs";
try
{
var response = httpClient.GetStringAsync(jwksUrl).GetAwaiter().GetResult();
var jwks = new Microsoft.IdentityModel.Tokens.JsonWebKeySet(response);
return jwks.Keys;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to fetch JWKS from {jwksUrl}: {ex.Message}");
return Array.Empty<Microsoft.IdentityModel.Tokens.SecurityKey>();
}
}
};
}
else
{
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true
};
}
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
Console.WriteLine($"JWT Authentication Failed: {context.Exception.Message}");
if (context.Exception.InnerException != null)
{
Console.WriteLine($"Inner Exception: {context.Exception.InnerException.Message}");
}
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
Console.WriteLine($"JWT Token Validated for user: {context.Principal?.Identity?.Name ?? "unknown"}");
return Task.CompletedTask;
},
OnChallenge = context =>
{
Console.WriteLine($"JWT Challenge: {context.Error}");
return Task.CompletedTask;
}
};
});
@@ -53,7 +128,29 @@ builder.Services.AddAuthorizationBuilder()
.AddPolicy("RequireGlobalAdmin", policy => policy.RequireAssertion(context =>
{
var realmAccess = context.User.FindFirst("realm_access")?.Value;
return realmAccess != null && realmAccess.Contains("\"admin\"");
if (string.IsNullOrEmpty(realmAccess))
return false;
try
{
using var doc = System.Text.Json.JsonDocument.Parse(realmAccess);
if (doc.RootElement.TryGetProperty("roles", out var rolesElement) &&
rolesElement.ValueKind == System.Text.Json.JsonValueKind.Array)
{
foreach (var role in rolesElement.EnumerateArray())
{
if (role.GetString() == "admin")
return true;
}
}
}
catch
{
// If JSON parsing fails, fallback to string contains check
return realmAccess.Contains("admin", StringComparison.OrdinalIgnoreCase);
}
return false;
}))
.AddPolicy("RequireManager", policy => policy.RequireRole("Manager"))
.AddPolicy("RequireMember", policy => policy.RequireRole("Manager", "Member"))
@@ -89,9 +186,14 @@ if (app.Environment.IsDevelopment())
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<TenantValidationMiddleware>();
app.UseAuthorization();
app.UseMiddleware<MemberSyncMiddleware>();
app.MapHealthChecks("/health/live", new Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions
@@ -121,9 +223,30 @@ app.MapGet("/weatherforecast", () =>
})
.WithName("GetWeatherForecast");
// Simple test endpoint for middleware validation tests
app.MapGet("/api/test", () => Results.Ok(new { message = "Test endpoint" }))
.RequireAuthorization();
app.MapGet("/api/debug/claims", (HttpContext context) =>
{
var claims = context.User.Claims.Select(c => new { c.Type, c.Value }).ToList();
var realmAccess = context.User.FindFirst("realm_access")?.Value;
// Check if the authorization header is present
var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
return Results.Ok(new
{
isAuthenticated = context.User.Identity?.IsAuthenticated ?? false,
authenticationType = context.User.Identity?.AuthenticationType,
claimCount = claims.Count,
claims = claims,
realmAccess = realmAccess,
hasAuthHeader = !string.IsNullOrEmpty(authHeader),
authHeaderPrefix = authHeader?.Substring(0, Math.Min(20, authHeader?.Length ?? 0))
});
});
app.MapTaskEndpoints();
app.MapShiftEndpoints();
app.MapClubEndpoints();
+6 -4
View File
@@ -43,6 +43,9 @@ services:
KC_HOSTNAME_STRICT: "false"
KC_PROXY: "edge"
KC_HTTP_PORT: "8081"
# Additional hostname for internal Docker communication
KC_HOSTNAME_ADMIN: "http://keycloak:8081"
KC_SPI_HOSTNAME_DEFAULT_ADMIN: "keycloak:8081"
ports:
- "8080:8081"
volumes:
@@ -64,15 +67,14 @@ services:
environment:
ASPNETCORE_ENVIRONMENT: Development
ConnectionStrings__DefaultConnection: "Host=postgres;Port=5432;Database=workclub;Username=workclub;Password=dev_password_change_in_production"
Keycloak__Authority: "http://192.168.65.254:8080/realms/workclub"
Keycloak__Authority: "http://keycloak:8081/realms/workclub"
Keycloak__Audience: "workclub-api"
Keycloak__TokenValidationParameters__ValidateIssuer: "false"
ports:
- "5001:8080"
extra_hosts:
- "localhost:host-gateway"
- "127.0.0.1:host-gateway"
- "keycloak:host-gateway"
- "localhost:172.18.0.1"
- "127.0.0.1:172.18.0.1"
working_dir: /app
volumes:
- ./backend:/app:cached