Search code examples
javasessionsession-variablessession-statehttpsession

How to kill any session on basis of just SessionID


Given that,

I have a

USER_ACTIVITY_LOG table

that contains

USER_ID, SESSION_ID, ACTIVITY_CODE(Login/LogOut/TimeOut) & ACTIVITY_TIME columns

in that. It updates all activities performed on the application in the table on basis of UserId & SessionId.

Problem Statement : I want to restrict logins to maximum 2 users with the same credentials on my application.

Say at a time 2 users are logged into the application with the same credentials (eg: admin/admin) and now 3rd user is trying to log into application with the same credentials. In such case the oldest logged in user session should be invalidated.

I have to query USER_ACTIVITY_LOG table on every user login and check number of users logged in with the same userId and are not logged out. If I get count of 2 users that are still logged in, I simply want to invalidate the session of the oldest user on basis of just SESSION_ID.

Is that possible ?

My project is on Java 8, Jboss 6.4, J2EE, Struts 2 & Oracle.


Solution

  • This is the fix I found out and I am using it as of now. No matter it will impact the performance a bit.

    public void expireSessionWithId(String sessionID)
    {  
         try { 
            MBeanServer server = java.lang.management.ManagementFactory.getPlatformMBeanServer();
    
            ObjectName objectName=new ObjectName("jboss.web:type=Manager,path=/test,host=default-host");
    
            // declare signature of the parameter
            String[] sig = { "java.lang.String"};
            // declare parameter
            Object[] opArgs1 = { sessionID };
            // call the method
            String value = (String) server.invoke(objectName, "expireSession",
                    opArgs1, sig);
    
            System.out.println(value);
        } catch (MalformedObjectNameException e) {
            //handle the exception
        } catch (InstanceNotFoundException e) {
            //handle the exception
        } catch (ReflectionException e) {
            //handle the exception
        } catch (MBeanException e) {
            //handle the exception
        }
    
    }