2

I'm trying to set a user's attribute after they register in my custom Keycloak extension. My event listener implementation looks as follows:

@AutoService(EventListenerProviderFactory.class)
public class EventListener implements EventListenerProvider {

    private final KeycloakSession session;
    public EventListener(KeycloakSession session) {
        this.session = session;
    }
    @Override
    public void onEvent(Event event) {
        if (event.getType() != EventType.REGISTER)
            return;
        
        RealmModel realm = session.realms().getRealm(event.getRealmId());
        UserModel user = session.users().getUserById(realm, event.getUserId());
        
        user.setSingleAttribute("hello", "world");
    }

    @Override
    public void onEvent(AdminEvent event, boolean includeRepresentation) {
        
    }

    @Override
    public void close() {

    }
}

My extension is recognized by Keycloak and successfully triggers onEvent() when an event occurs (hence why I didn't include the factory class).

However, the attribute isn't added to the user. How do I actually persist the changes to the user?

While searching for a solution to the above, I came across this discussion of a very similar issue. Extending RegistrationUserCreation instead of EventListenerProvider and using the solution given by @dvlpphb did actually manage to solve my problem; however, the solution only worked when overriding the RegistrationUserCreation's validate() method, which is called every time the user attempts to register.

If anyone knows a way to set a user attribute without EventListenerProvider through RegistrationUserCreation's success() callback, that would also solve my issue.

Thank you!

Twisted Tea
  • 49
  • 11
  • Your solution should work, as far as I can see. You should try to add some debug code. (I have a similar solution running, but not using the register event. But I made some test and it seems to work) – csbrogi Nov 07 '22 at 12:00
  • 1
    I have the same probleme, the attribute is created and set and I can read the value in the scope of the method where I created it, but on next event call the value isn't here – user1767316 Jan 16 '23 at 07:59

0 Answers0