I need to force log out the user when the same user log in from somewhere else
I have stored session id (which is from HttpServletRequest) with user as key value pair in a HashMap. Whenever a logged in user try to log in from different browser, I need to session out the previous log in. I do remove it from the HashMap. Still the previous user is in logged in state. How do I force shutdown that?
CodePudding user response:
You have to keep track of the session objects instead of just the session IDs in your map:
Map<String, HttpSession> sessionsByUsername = new HashMap<>();
For each request, use the username to look up the session from the map:
HttpSession session = request.getSession();
String userName = session.getAttribute(USER_NAME);
HttpSession cachedSession = sessionsByUsername.get(userName);
If it is not present, put a new entry in the map:
if (cachedSession == null) {
sessionsByUsername.put(userName, session);
}
...
If it is present and different, invalidate the old session and replace it with the new session in the map:
...
else if (session != cachedSession) {
sessionsByUsername.put(userName, session);
cachedSession.invalidate();
}
Note that this is not thread safe (simultaneous requests might be processing with the cached session, when it is suddenly invalidated) and it will only work on a single server instance. If you are running on multiple nodes in a cluster things like session replication will ruin this scheme. To make it work more robustly you will need to resort to a single sign on (SSO) solution which manages the authentication state separately.
EDIT: the logic can be simplified to:
HttpSession session = request.getSession();
String userName = session.getAttribute(USER_NAME);
HttpSession cachedSession = sessionsByUsername.get(userName);
if (session != cachedSession) {
sessionsByUsername.put(userName, session);
if (cachedSession != null) {
cachedSession.invalidate();
}
}
https://docs.oracle.com/cd/E19146-01/819-2634/abxdj/index.html