3.0 KiB
Keycloak Session Timeout Fix
Issue Analysis
Sessions are expiring after 5 minutes instead of the expected 30+ minutes due to Keycloak configuration issues.
Root Cause
From your Keycloak settings screenshot, there are two critical issues:
1. Refresh Tokens Are Disabled
- Current Setting: "Revoke Refresh Token" is set to DISABLED
- Problem: This actually means refresh tokens are disabled (confusing UI naming)
- Impact: Users can't extend their sessions automatically
2. Short User-Initiated Action Lifespan
- Current Setting: 5 minutes
- Problem: This overrides access token lifespan for certain user actions
- Impact: Forces re-authentication after 5 minutes of activity
Required Keycloak Configuration Changes
Step 1: Enable Refresh Tokens
In your Keycloak realm settings:
- Navigate to Realm Settings → Tokens
- Find "Revoke Refresh Token"
- Set it to ENABLED (this enables refresh tokens)
Step 2: Increase Token Lifespans
Update these settings in Realm Settings → Tokens:
- Access Token Lifespan: 30 minutes ✅ (already correct)
- User-Initiated Action Lifespan: Change from 5 minutes to 30 minutes
- Client Login Timeout: Change from 1 minute to 30 minutes
- Access Token Lifespan For Implicit Flow: Set to 15 minutes
Step 3: Verify Client Settings
In Clients → [Your Client] → Settings:
- Ensure "Standard Flow Enabled" is ON
- Ensure "Direct Access Grants Enabled" is ON
Expected Results After Changes
- Sessions will last 30 minutes of inactivity
- Active users will have tokens refreshed automatically 2 minutes before expiry
- No unexpected logouts during normal use
Application Status
Your application already has:
- ✅ Token refresh endpoint (
/api/auth/refresh) - ✅ Automatic refresh plugin (
plugins/01.auth-refresh.client.ts) - ✅ Session caching in authentication middleware
- ✅ Proper token storage and handling
Testing After Changes
- Make the Keycloak configuration changes above
- Clear your browser cookies and cache
- Log in fresh
- Verify you can stay logged in for 30+ minutes
- Check that tokens refresh automatically (look for
[AUTH_REFRESH]logs in browser console)
Implementation Priority
HIGH PRIORITY:
- Enable refresh tokens (Step 1)
- Increase User-Initiated Action Lifespan to 30 minutes (Step 2)
MEDIUM PRIORITY: 3. Update other token lifespans 4. Verify client settings
Current Workaround
Until you make these Keycloak changes, the authentication middleware has a 30-second cache that reduces the frequency of auth checks, but it won't prevent the underlying 5-minute timeout.
Next Steps
- Immediate: Update your Keycloak configuration as described above
- After changes: Test thoroughly to ensure 30-minute sessions work
- Monitor: Check browser console logs for any authentication errors
The good news is your application code is already properly set up for longer sessions - it's just the Keycloak configuration that needs adjustment.