port-nimara-client-portal/middleware/authentication.ts

118 lines
4.0 KiB
TypeScript
Raw Normal View History

import { sessionManager } from '~/server/utils/session-manager'
export default defineNuxtRouteMiddleware(async (to) => {
// Skip auth for SSR
if (import.meta.server) return;
2025-02-16 13:10:19 +01:00
// Check if auth is required (default true unless explicitly set to false)
const isAuthRequired = to.meta.auth !== false;
MAJOR: Replace keycloak-js with nuxt-oidc-auth for seamless SSO integration ## **SOLUTION: Migrate to Server-Side OIDC Authentication** This completely replaces the problematic keycloak-js client-side implementation with nuxt-oidc-auth, eliminating all CORS and iframe issues. ### **Benefits:** - **No more CORS errors** - Server-side OAuth flow - **No iframe dependencies** - Eliminates cross-domain issues - **Works with nginx proxy** - No proxy configuration conflicts - **Better security** - Tokens handled server-side - **Cleaner integration** - Native Nuxt patterns - **Maintains Directus compatibility** - Dual auth support ### **Installation & Configuration:** - Added uxt-oidc-auth module to nuxt.config.ts - Configured Keycloak provider with proper OIDC settings - Updated environment variables for security keys ### **Code Changes:** #### **Authentication Flow:** - **middleware/authentication.ts** - Updated to check both Directus + OIDC auth - **composables/useUnifiedAuth.ts** - Migrated to use useOidcAuth() - **pages/login.vue** - Updated SSO button to use oidcLogin('keycloak') #### **Configuration:** - **nuxt.config.ts** - Added OIDC provider configuration - **.env.example** - Updated with nuxt-oidc-auth environment variables - Removed old Keycloak runtime config #### **Cleanup:** - Removed keycloak-js dependency from package.json - Deleted obsolete files: - composables/useKeycloak.ts - pages/auth/callback.vue - server/utils/keycloak-oauth.ts - server/api/debug/ directory ### **Authentication Routes (Auto-Generated):** - /auth/keycloak/login - SSO login endpoint - /auth/keycloak/logout - SSO logout endpoint - /auth/keycloak/callback - OAuth callback (handled automatically) ### **Security Setup Required:** Environment variables needed for production: - NUXT_OIDC_PROVIDERS_KEYCLOAK_CLIENT_SECRET - NUXT_OIDC_TOKEN_KEY (base64 encoded 32-byte key) - NUXT_OIDC_SESSION_SECRET (48-character random string) - NUXT_OIDC_AUTH_SESSION_SECRET (48-character random string) ### **Expected Results:** SSO login should work without CORS errors Compatible with nginx proxy setup Maintains existing Directus authentication Server-side session management Automatic token refresh Ready for container rebuild and production testing!
2025-06-14 15:58:03 +02:00
if (!isAuthRequired) {
console.log('[MIDDLEWARE] Auth not required for route:', to.path);
MAJOR: Replace keycloak-js with nuxt-oidc-auth for seamless SSO integration ## **SOLUTION: Migrate to Server-Side OIDC Authentication** This completely replaces the problematic keycloak-js client-side implementation with nuxt-oidc-auth, eliminating all CORS and iframe issues. ### **Benefits:** - **No more CORS errors** - Server-side OAuth flow - **No iframe dependencies** - Eliminates cross-domain issues - **Works with nginx proxy** - No proxy configuration conflicts - **Better security** - Tokens handled server-side - **Cleaner integration** - Native Nuxt patterns - **Maintains Directus compatibility** - Dual auth support ### **Installation & Configuration:** - Added uxt-oidc-auth module to nuxt.config.ts - Configured Keycloak provider with proper OIDC settings - Updated environment variables for security keys ### **Code Changes:** #### **Authentication Flow:** - **middleware/authentication.ts** - Updated to check both Directus + OIDC auth - **composables/useUnifiedAuth.ts** - Migrated to use useOidcAuth() - **pages/login.vue** - Updated SSO button to use oidcLogin('keycloak') #### **Configuration:** - **nuxt.config.ts** - Added OIDC provider configuration - **.env.example** - Updated with nuxt-oidc-auth environment variables - Removed old Keycloak runtime config #### **Cleanup:** - Removed keycloak-js dependency from package.json - Deleted obsolete files: - composables/useKeycloak.ts - pages/auth/callback.vue - server/utils/keycloak-oauth.ts - server/api/debug/ directory ### **Authentication Routes (Auto-Generated):** - /auth/keycloak/login - SSO login endpoint - /auth/keycloak/logout - SSO logout endpoint - /auth/keycloak/callback - OAuth callback (handled automatically) ### **Security Setup Required:** Environment variables needed for production: - NUXT_OIDC_PROVIDERS_KEYCLOAK_CLIENT_SECRET - NUXT_OIDC_TOKEN_KEY (base64 encoded 32-byte key) - NUXT_OIDC_SESSION_SECRET (48-character random string) - NUXT_OIDC_AUTH_SESSION_SECRET (48-character random string) ### **Expected Results:** SSO login should work without CORS errors Compatible with nginx proxy setup Maintains existing Directus authentication Server-side session management Automatic token refresh Ready for container rebuild and production testing!
2025-06-14 15:58:03 +02:00
return;
}
// Skip auth check if we're already on the login page to prevent redirect loops
if (to.path === '/login' || to.path.startsWith('/auth')) {
return;
}
console.log('[MIDDLEWARE] Checking authentication for route:', to.path);
// Use session manager for centralized session handling
const nuxtApp = useNuxtApp();
const cacheKey = 'auth:session:cache';
const baseExpiry = 3 * 60 * 1000; // 3 minutes base cache
const jitter = Math.floor(Math.random() * 10000); // 0-10 seconds jitter
const cacheExpiry = baseExpiry + jitter; // Prevent thundering herd
try {
// Use SessionManager for deduped session checks
const sessionData = await sessionManager.checkSession({
nuxtApp,
cacheKey,
cacheExpiry,
fetchFn: async () => {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000); // 10 second timeout
try {
const result = await $fetch('/api/auth/session', {
signal: controller.signal,
retry: 2,
retryDelay: 1000,
onRetry: ({ retries }: { retries: number }) => {
console.log(`[MIDDLEWARE] Retrying auth check (attempt ${retries + 1})`)
},
onResponseError({ response }) {
// Clear cache only on actual auth errors, not 404s or other errors
if (response.status === 401) {
console.log('[MIDDLEWARE] Unauthorized error detected, clearing cache')
sessionManager.clearCache();
delete nuxtApp.payload.data?.authState;
} else if (response.status === 403) {
console.log('[MIDDLEWARE] Forbidden error detected, partial cache clear')
// Don't clear cache on 403 as user is authenticated but lacks permissions
}
// Ignore 404s and other errors - they're not authentication issues
}
}) as any;
clearTimeout(timeout);
return result;
} catch (error) {
clearTimeout(timeout);
throw error;
}
}
});
// Store auth state for components
if (!nuxtApp.payload.data) {
nuxtApp.payload.data = {};
}
nuxtApp.payload.data.authState = {
user: sessionData.user,
authenticated: sessionData.authenticated,
groups: sessionData.groups || []
};
console.log('[MIDDLEWARE] Session check result:', {
authenticated: sessionData.authenticated,
hasUser: !!sessionData.user,
userId: sessionData.user?.id,
groups: sessionData.groups || [],
fromCache: sessionData.fromCache,
reason: sessionData.reason
});
2025-02-16 13:10:19 +01:00
if (sessionData.authenticated && sessionData.user) {
console.log('[MIDDLEWARE] User authenticated, allowing access');
// Check for any auth errors from authorization middleware
if (nuxtApp.payload.authError) {
const toast = useToast();
toast.error(String(nuxtApp.payload.authError));
delete nuxtApp.payload.authError;
}
return;
}
2025-02-16 13:10:19 +01:00
console.log('[MIDDLEWARE] No valid authentication found, redirecting to login');
MAJOR: Replace keycloak-js with nuxt-oidc-auth for seamless SSO integration ## **SOLUTION: Migrate to Server-Side OIDC Authentication** This completely replaces the problematic keycloak-js client-side implementation with nuxt-oidc-auth, eliminating all CORS and iframe issues. ### **Benefits:** - **No more CORS errors** - Server-side OAuth flow - **No iframe dependencies** - Eliminates cross-domain issues - **Works with nginx proxy** - No proxy configuration conflicts - **Better security** - Tokens handled server-side - **Cleaner integration** - Native Nuxt patterns - **Maintains Directus compatibility** - Dual auth support ### **Installation & Configuration:** - Added uxt-oidc-auth module to nuxt.config.ts - Configured Keycloak provider with proper OIDC settings - Updated environment variables for security keys ### **Code Changes:** #### **Authentication Flow:** - **middleware/authentication.ts** - Updated to check both Directus + OIDC auth - **composables/useUnifiedAuth.ts** - Migrated to use useOidcAuth() - **pages/login.vue** - Updated SSO button to use oidcLogin('keycloak') #### **Configuration:** - **nuxt.config.ts** - Added OIDC provider configuration - **.env.example** - Updated with nuxt-oidc-auth environment variables - Removed old Keycloak runtime config #### **Cleanup:** - Removed keycloak-js dependency from package.json - Deleted obsolete files: - composables/useKeycloak.ts - pages/auth/callback.vue - server/utils/keycloak-oauth.ts - server/api/debug/ directory ### **Authentication Routes (Auto-Generated):** - /auth/keycloak/login - SSO login endpoint - /auth/keycloak/logout - SSO logout endpoint - /auth/keycloak/callback - OAuth callback (handled automatically) ### **Security Setup Required:** Environment variables needed for production: - NUXT_OIDC_PROVIDERS_KEYCLOAK_CLIENT_SECRET - NUXT_OIDC_TOKEN_KEY (base64 encoded 32-byte key) - NUXT_OIDC_SESSION_SECRET (48-character random string) - NUXT_OIDC_AUTH_SESSION_SECRET (48-character random string) ### **Expected Results:** SSO login should work without CORS errors Compatible with nginx proxy setup Maintains existing Directus authentication Server-side session management Automatic token refresh Ready for container rebuild and production testing!
2025-06-14 15:58:03 +02:00
return navigateTo('/login');
} catch (error: any) {
console.error('[MIDDLEWARE] Auth check failed:', error);
// Show warning for cached results due to network errors
if (error.reason === 'NETWORK_ERROR_CACHED') {
const toast = useToast();
toast.warning('Network connectivity issue - using cached authentication');
}
MAJOR: Replace keycloak-js with nuxt-oidc-auth for seamless SSO integration ## **SOLUTION: Migrate to Server-Side OIDC Authentication** This completely replaces the problematic keycloak-js client-side implementation with nuxt-oidc-auth, eliminating all CORS and iframe issues. ### **Benefits:** - **No more CORS errors** - Server-side OAuth flow - **No iframe dependencies** - Eliminates cross-domain issues - **Works with nginx proxy** - No proxy configuration conflicts - **Better security** - Tokens handled server-side - **Cleaner integration** - Native Nuxt patterns - **Maintains Directus compatibility** - Dual auth support ### **Installation & Configuration:** - Added uxt-oidc-auth module to nuxt.config.ts - Configured Keycloak provider with proper OIDC settings - Updated environment variables for security keys ### **Code Changes:** #### **Authentication Flow:** - **middleware/authentication.ts** - Updated to check both Directus + OIDC auth - **composables/useUnifiedAuth.ts** - Migrated to use useOidcAuth() - **pages/login.vue** - Updated SSO button to use oidcLogin('keycloak') #### **Configuration:** - **nuxt.config.ts** - Added OIDC provider configuration - **.env.example** - Updated with nuxt-oidc-auth environment variables - Removed old Keycloak runtime config #### **Cleanup:** - Removed keycloak-js dependency from package.json - Deleted obsolete files: - composables/useKeycloak.ts - pages/auth/callback.vue - server/utils/keycloak-oauth.ts - server/api/debug/ directory ### **Authentication Routes (Auto-Generated):** - /auth/keycloak/login - SSO login endpoint - /auth/keycloak/logout - SSO logout endpoint - /auth/keycloak/callback - OAuth callback (handled automatically) ### **Security Setup Required:** Environment variables needed for production: - NUXT_OIDC_PROVIDERS_KEYCLOAK_CLIENT_SECRET - NUXT_OIDC_TOKEN_KEY (base64 encoded 32-byte key) - NUXT_OIDC_SESSION_SECRET (48-character random string) - NUXT_OIDC_AUTH_SESSION_SECRET (48-character random string) ### **Expected Results:** SSO login should work without CORS errors Compatible with nginx proxy setup Maintains existing Directus authentication Server-side session management Automatic token refresh Ready for container rebuild and production testing!
2025-06-14 15:58:03 +02:00
return navigateTo('/login');
2025-02-16 13:10:19 +01:00
}
});