Reputation: 115
I'm developing a Spring Boot application with an Angular frontend, and I'm using Keycloak for authentication and authorization. The application relies on Server-Sent Events (SSE) for real-time information transfer.
To ensure that users can only be logged in from one device at a time, I have configured Keycloak's authentication flow to "Terminate oldest session". However, I've encountered the following issues:
Token Persistence: When a user logs in from a new device, Keycloak terminates the session on the previous device, but the JWT token remains valid. The user can continue to work in the application until they manually refresh the page, at which point they are logged out. This behavior is not ideal as I want the user to be automatically logged out from the previous device.
SSE Connection Issues: With multiple active logins, the SSE connection can become problematic. Ideally, each user should only have one active connection.
One workaround I found is to constantly ping Keycloak to check the user's session, but this approach seems inefficient and resource-intensive, especially with multiple users: https://onyalioscar.medium.com/implementing-user-single-session-with-automatic-log-out-using-keycloak-java-spring-boot-and-ef23b0804417
How can I ensure that when a user logs in from a new device, it is automatically logged out from the previous device without the need for a manual refresh?
Upvotes: 1
Views: 414
Reputation: 58404
You have to perform long polling like 30s
using the approach you have mentioned, which is the easiest method to handle the problem and the long duration eases the load on the server.
But as far as I know, when the user makes an API call using an expired JWT token, the API will give you a 401 Unauthorized error.
If the JWT token is valid, then validate the session also, then make the API throw 401 error
You can use angular interceptors to check for this error and logout off the application, hence deleting the JWT token also.
Upvotes: 0