Disable user in session SPI

Hi!
Is there a way that i can update an user data on a SPI?

This is my actual code:

public void onEvent(Event event){
        logger.info("Event fired => " + event.getType());

        if(EventType.LOGIN.equals(event.getType())){
            logger.info("Log-in called!");
            RealmModel realm = keycloakSession.getContext().getRealm();
            InMemoryUserAdapter user = new InMemoryUserAdapter(keycloakSession, realm, event.getUserId());
            int total_sessions = keycloakSession.sessions().getUserSessions(realm, user).size();
            logger.info("Sessions: " + total_sessions);

            if(total_sessions > 1){
                logger.info("Disabling user...");
                user.setEnabled(false);
            }
        }
    }

I want to disable an user when he has more than 2 sessions active, but when i use setEnabled, it doesn’t update the user data. I’ve already reading the docs and i’ve seen that the UserRepresentation class have an updateUser() method but i don’t know if i can do that.

Thanks!

EDIT: My keycloak version is 12.0.4

I don’t think that method of getting the user will work if you want to be able to update it. Try:

    UserModel user = keycloakSession.users().getUserById(event.getUserId(), realm);

I’ve already tried that but doesn’t work for me. To be able to update an user i got the realmresource, then the userprovider and userresource and finally works with updateUser() method in UserResource

Thanks for your time!

1 Like