Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to manually kill a specific HttpSession by ID?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 instance. If you are running 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.

https://docs.oracle.com/cd/E19146-01/819-2634/abxdj/index.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading