2.7 KiB
2.7 KiB
Iframe Logout Session Invalidation Fix
Problem
When a user logs out from an application inside an iframe:
- The iframe application calls Keycloak logout endpoint
- Keycloak session is invalidated
- NextAuth dashboard still has a valid JWT token
- When NextAuth tries to refresh the token, Keycloak returns:
{ error: 'invalid_grant', error_description: 'Session not active' } - This causes a
JWT_SESSION_ERRORand the user sees errors but isn't automatically signed out
Root Cause
The refreshAccessToken function was catching all errors generically and setting error: "RefreshAccessTokenError". When the session callback received this error, it would throw, causing a JWT_SESSION_ERROR but not properly signing the user out.
Solution
1. Detect Session Invalidation
In refreshAccessToken, we now specifically detect when Keycloak returns invalid_grant with "Session not active":
if (refreshedTokens.error === 'invalid_grant' ||
refreshedTokens.error_description?.includes('Session not active') ||
refreshedTokens.error_description?.includes('Token is not active')) {
return {
...token,
error: "SessionNotActive",
};
}
2. Clear Tokens in JWT Callback
When we detect SessionNotActive, we clear the tokens in the JWT callback:
if (refreshedToken.error === "SessionNotActive") {
return {
...refreshedToken,
accessToken: undefined,
refreshToken: undefined,
idToken: undefined,
};
}
3. Return Null in Session Callback
When tokens are missing or session is invalidated, the session callback returns null, which makes NextAuth treat the user as unauthenticated:
if (token.error === "SessionNotActive" || !token.accessToken) {
return null as any; // NextAuth will treat user as unauthenticated
}
Result
Now when a user logs out from an iframe application:
- Keycloak session is invalidated
- NextAuth detects the invalid session on next token refresh
- Tokens are cleared
- Session callback returns null
- User is automatically treated as unauthenticated
- NextAuth redirects to sign-in page (via AuthCheck component)
Files Modified
app/api/auth/options.ts:- Enhanced
refreshAccessTokento detectinvalid_granterrors - Clear tokens when session is invalidated
- Return null from session callback when session is invalid
- Enhanced
Testing
To test this fix:
- Log in to the dashboard
- Open an iframe application
- Log out from the iframe application
- Wait for NextAuth to try to refresh the token (or trigger a page refresh)
- User should be automatically signed out and redirected to sign-in
Date: 2024
Status: ✅ Fixed
Version: 1.0