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!
This commit is contained in:
Matt 2025-06-15 15:47:36 +02:00
parent 8048cde5b6
commit bff185e4ac
1 changed files with 10 additions and 7 deletions

View File

@ -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