Concurrent Session disable

Hi,

How can we disable concurrent sessions on jmix web application. The other logged in user session should be expired when a same user logins from other device.

1 Like

We did this logic on the LoginScreen.
Just add your code to the ‘login’ method before calling the authentication method.
There is no example of cod for illustration.

...
public class LoginScreen extends Screen {
//Standard screen code generated by Jmix
private void login() {
        String username = usernameField.getValue();
        String password = passwordField.getValue();

      .....
      .....
      .....

//Added our code to verify that such a user is already working and optional kill old session 
        if (checkOtherUserSessionsPresent(username)) {
            String finalUsername = username;
            dialogs.createOptionDialog()
                    .withCaption(messages.getMessage("OptionDialog.caption"))
                    .withMessage(messages.getMessage("OptionDialog.message"))
                    .withActions(
                            new DialogAction(DialogAction.Type.YES, Action.Status.PRIMARY)
                                    .withHandler(e -> {
                                        killSession(finalUsername);
                                        tryAuthenticate(finalUsername, password);
                                    }),
                            new DialogAction(DialogAction.Type.NO)
                    )
                    .show();
        } else {
            //Standard Authentication
            tryAuthenticate(username, password);
        }
    }
}

//Our method to check the user's session
private Boolean checkOtherUserSessionsPresent(String username) {
        long userSessionCount = 0L;
        List<UserSession> sessionList = userSessions.sessions().collect(Collectors.toList());
        if (!sessionList.isEmpty()) {
            userSessionCount = sessionList.stream().filter(s -> s.getPrincipalName().equals(username)).count();
        }
        return userSessionCount > 0;
}

//Our method to delete an old user session
private void killSession(String username){
        userSessions.sessions()
                .filter(s -> s.getPrincipalName().equals(username))
                .forEach((os) -> {
                    os.getSessionInformation().expireNow();
                    log.warn("Session id = {} user [ {} ] has been aborted due to login from another device or browser.",
                            os.getSessionId(), os.getPrincipalName());
                });
}


//Standard screen code generated by Jmix
...
...
...
}
1 Like

Thanks for the answer,

I was not able to figure out where or how did you initialize userSessions object that is used in checkOtherUserSessionsPresent method.

1 Like

Use injection.

@Autowired
    private UserSessions userSessions;

1 Like

It worked after adding audit plugin. Thanks.

2 Likes