monacousa-portal/LOGIN_FIX_SUMMARY.md

244 lines
6.8 KiB
Markdown
Raw Normal View History

# MonacoUSA Portal - Login Issue Fix Summary
## Issue Description
The login functionality was experiencing redirect failures after successful authentication. Users could successfully authenticate with Keycloak, but the redirect to the dashboard was failing with 502 Bad Gateway errors and CORS issues.
## Root Causes Identified
1. **Service Worker Interference**: The PWA service worker was caching authentication-related routes, causing conflicts during login redirects.
2. **Cookie Domain Issues**: The session cookie was being set with an explicit domain (`.monacousa.org`) which could cause issues in certain deployment scenarios.
3. **Redirect Method**: Using `window.location.href` for redirects was causing hard page reloads that conflicted with the SPA architecture.
4. **Nginx Proxy Timeouts**: Missing proxy timeout configurations could cause 502 errors during authentication flows.
## Fixes Applied
### 1. PWA Service Worker Configuration (`nuxt.config.ts`)
**Changes Made:**
- Added authentication-related paths to `navigateFallbackDenylist`
- Reduced API cache duration from 24 hours to 5 minutes
- Added `cleanupOutdatedCaches: true` for better cache management
```typescript
navigateFallbackDenylist: [
/^\/api\//,
/^\/auth\//,
/^\/login/,
/^\/dashboard/
],
```
**Why This Fixes It:**
- Prevents service worker from intercepting authentication flows
- Ensures fresh API responses during login
- Eliminates cache-related redirect conflicts
### 2. Cookie Domain Fix (`server/api/auth/direct-login.post.ts`)
**Changes Made:**
- Removed explicit cookie domain setting
- Let cookies default to the current domain
```typescript
// Before: domain: cookieDomain,
// After: No domain specified (defaults to current domain)
setCookie(event, 'monacousa-session', cookieValue, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge,
path: '/',
});
```
**Why This Fixes It:**
- Eliminates cross-domain cookie issues
- Ensures cookies work correctly in all deployment scenarios
- Follows browser security best practices
### 3. Login Page Refactor (`pages/login.vue`)
**Changes Made:**
- Replaced direct API calls with `useAuth()` composable
- Removed `window.location.href` redirect
- Improved state management integration
```typescript
// Before: window.location.href = response.redirectTo || '/dashboard';
// After: Uses useAuth().login() which handles navigation properly
const result = await login({
username: credentials.value.username,
password: credentials.value.password,
rememberMe: credentials.value.rememberMe
});
```
**Why This Fixes It:**
- Proper SPA navigation without hard page reloads
- Better integration with Nuxt's authentication state
- Eliminates service worker conflicts during navigation
### 4. Nginx Proxy Configuration (`nginx-portal.conf`)
**Changes Made:**
- Added proxy timeout configurations
- Improved buffer settings for better performance
```nginx
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
```
**Why This Fixes It:**
- Prevents 502 errors during authentication flows
- Handles larger response payloads better
- Improves overall proxy stability
## Testing the Fix
### 1. Clear Browser Cache
```bash
# Clear all browser data for portal.monacousa.org
# Or use incognito/private browsing mode
```
### 2. Restart Services
```bash
# Restart Nginx
sudo systemctl restart nginx
# Restart the Nuxt application
# (depends on your deployment method)
```
### 3. Test Login Flow
1. Navigate to `https://portal.monacousa.org/login`
2. Enter valid credentials
3. Verify successful redirect to dashboard
4. Check browser console for errors
### 4. Use Debug Script
```bash
# Run the debug script to test API endpoints
node debug-login.js
```
## Verification Steps
### Browser Console Checks
- No CORS errors should appear
- No 502 Bad Gateway errors
- Service worker should not intercept auth routes
### Network Tab Verification
- Login POST request should return 200
- Session cookie should be set correctly
- Dashboard redirect should work without errors
### Server Logs
- Should show successful login messages
- No cookie domain warnings
- Proper session creation logs
## Troubleshooting
### If Login Still Fails
1. **Check Service Worker**
```javascript
// In browser console
navigator.serviceWorker.getRegistrations().then(registrations => {
registrations.forEach(registration => registration.unregister());
});
```
2. **Verify Cookie Settings**
- Check browser dev tools > Application > Cookies
- Ensure `monacousa-session` cookie is set
- Verify cookie domain matches current domain
3. **Check Nginx Logs**
```bash
tail -f /var/log/nginx/portal.monacousa.org.error.log
```
4. **Verify Keycloak Configuration**
- Ensure all environment variables are set
- Test Keycloak connectivity
- Verify client configuration
### Common Issues
1. **Still Getting 502 Errors**
- Check if Nuxt application is running on port 6060
- Verify nginx can connect to backend
- Check firewall settings
2. **Cookies Not Being Set**
- Verify HTTPS is working correctly
- Check if secure flag is appropriate for environment
- Ensure no conflicting cookie policies
3. **Service Worker Issues**
- Clear browser cache completely
- Unregister service worker manually
- Check PWA configuration
## Environment Variables
Ensure these are properly configured:
```env
# Keycloak Configuration
NUXT_KEYCLOAK_ISSUER=https://auth.monacousa.org/realms/monacousa
NUXT_KEYCLOAK_CLIENT_ID=monacousa-portal
NUXT_KEYCLOAK_CLIENT_SECRET=your-secret
# Session Security
NUXT_SESSION_SECRET=your-48-character-secret
NUXT_ENCRYPTION_KEY=your-32-character-key
# Public Configuration
NUXT_PUBLIC_DOMAIN=monacousa.org
```
## Deployment Notes
1. **Nginx Configuration**
- Reload nginx after configuration changes
- Test configuration with `nginx -t`
2. **Application Restart**
- Restart Nuxt application to pick up changes
- Clear any application-level caches
3. **SSL Certificates**
- Ensure SSL certificates are valid
- Verify HTTPS is working correctly
## Success Indicators
✅ Login form submits without errors
✅ User is redirected to dashboard
✅ Session is maintained across page refreshes
✅ No console errors related to authentication
✅ Health check endpoint returns "healthy"
✅ Service worker doesn't interfere with auth flows
## Files Modified
1. `nuxt.config.ts` - PWA service worker configuration
2. `pages/login.vue` - Login page refactor
3. `server/api/auth/direct-login.post.ts` - Cookie domain fix
4. `nginx-portal.conf` - Proxy timeout configuration
5. `debug-login.js` - Debug script (new file)
6. `LOGIN_FIX_SUMMARY.md` - This documentation (new file)
The fixes address the core issues causing login redirect failures and should provide a stable authentication experience.