From bff185e4ac64b96e85b234375624b62a3e8567ee Mon Sep 17 00:00:00 2001 From: Matt Date: Sun, 15 Jun 2025 15:47:36 +0200 Subject: [PATCH] FIX: Authentication middleware for custom Keycloak auth ## **Fixed 502 Error After Login:** ### **Issue:** - After successful Keycloak authentication, users got 502 Bad Gateway error - Middleware was still trying to use removed useOidcAuth() composable - This caused the app to crash when accessing dashboard ### **Solution:** - Replaced useOidcAuth() with direct session API call - Uses /api/auth/session endpoint to check authentication - Maintains dual auth support (Directus + Keycloak) - Added proper error handling to prevent crashes ### **Authentication Flow Now:** 1. **Check Directus auth** first (existing users) 2. **Check custom Keycloak session** via API call 3. **Allow access** if either authentication succeeds 4. **Redirect to login** if no authentication found ### **Files Changed:** - middleware/authentication.ts - Updated to use custom auth system ## **Result:** The complete authentication flow should now work: 1. Login via Keycloak SSO 2. Token exchange and session creation 3. Middleware validates session properly 4. Dashboard loads without 502 errors ## **Ready to Test:** Deploy and test the complete SSO flow - should work end-to-end! --- middleware/authentication.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/middleware/authentication.ts b/middleware/authentication.ts index 64c0af6..95ff241 100644 --- a/middleware/authentication.ts +++ b/middleware/authentication.ts @@ -19,7 +19,7 @@ export default defineNuxtRouteMiddleware(async (to) => { const user = await fetchUser(); setUser(user.value); } catch (error) { - // Directus auth failed, continue to check OIDC + // Directus auth failed, continue to check custom Keycloak auth } } @@ -28,12 +28,15 @@ export default defineNuxtRouteMiddleware(async (to) => { return; } - // Check OIDC auth (Keycloak) - const { user: oidcUser, loggedIn } = useOidcAuth(); - - if (loggedIn.value && oidcUser.value) { - // User authenticated with Keycloak via OIDC - return; + // Check custom Keycloak auth via session API + try { + const sessionData = await $fetch('/api/auth/session') as any; + if (sessionData.authenticated && sessionData.user) { + // User authenticated with Keycloak + return; + } + } catch (error) { + // Session check failed, continue to redirect } // No authentication found, redirect to login