2
votes

I am using Keycloak (KC) as my identity broker with OIDC.

1) Browse client application and press login button

2) Behind the scenes login button will call KC auth end point which will display IDP login page

3) User1 bookmarks the login page and enters credentials and start using the client website

4) User1 closes browser without signing out

5) User2 comes immediately and clicks on bookmarked page which displays IDP login page

6) User2 enters credentials and gets following error:

[Error Message][1] [1]: https://i.stack.imgur.com/vn83h.png

7)Once user press on "back to application", user1 screen get displayed (which exposes user1 information to user2)

How can I expire user1's session if it is active when user2 tries to login using IDP login page directly without any problem.

1
Can someone help??hbogo1

1 Answers

0
votes

You have to implement a custom authenticator and add it to your authentication flow in Keycloak. Implement the Authenticator interface of Keycloak.

First, you need to get the list of sessions of the current user as follows:

List<UserSessionModel> userSessions = session.sessions().getUserSessions(context.getRealm(), context.getUser());

session is a KeycloakSession. The context can be accessed inside the method authenticate you are going to override next. Here we can start implementing the behaviour you are looking for:

 private void logoutOldestSession(List<UserSessionModel> userSessions) {
        logger.info("Logging out oldest session");
        Optional<UserSessionModel> oldest = userSessions.stream().sorted(Comparator.comparingInt(UserSessionModel::getStarted)).findFirst();
        oldest.ifPresent(userSession -> AuthenticationManager.backchannelLogout(session, userSession, true));
    }

Don't forget to deploy the jar file containing this behavior under deployments of your Keycloak distribution. Also, you have to reference your authenticator under /META-INF/services.