I have a JSF login page using form authentication. I login users by calling HttpServletRequest.login(username, password). Logging out is done by first calling ExternalContext.invalidateSession() and then calling HttpServletRequest.logout() for the current user.
My plan is to keep track of the logged in user in an application scoped list by adding to the list anytime a user logs in and removing from the list when a user logs out.
I have two concerns with this approach:
-
If a user that was already logged in tries to log in again without first logging out, I want to invalidate the existing session and do some cleanup. How do I access the session for a given logged in user? I could also use this functionality to forcefully logout some users.
-
If a session expires (e.g. timeout) I want to remove the user from the list of logged in users. How do I listen for a session expiration?
Maintain a
Map<User, HttpSession> loginsin application scope yourself. During login, check iflogins.put(user, session)doesn’t returnnulland then invalidate it.Let the
UserimplementHttpSessionBindingListenerand implementvalueUnbound()accordingly so that it does alogins.remove(this). Or, if you don’t have control overUser, then implementHttpSessionListener#sessionDestroyed()instead to perform the remove.Unrelated to the concrete problem, calling
HttpServletRequest#logout()is unnecessary if you already invalidate the session. The user is tied to the session anyway.