Last Login Time

Hi Everyone

I already create a custom event listener, it have a capability to listen to Login Event. So when a user login, this listener will persist into the user’s attribute the time his/her logged in.
I also build a service use Keycloak Admin client library with Java to retrieve the user data.

The problem is, when i retrieve that user data via the service, it doesn’t show the latest data of the user-attribute.

Let’s say the user A logged in at 11:00 AM. The service show the 11:00 AM. But after user A login again at 11:30 AM, the service show still 11:00 AM.

Is there any configuration or is there a suggestion what best practices to persist this login time via my custom event listener ?

Already found the solution. User UserModel to update User’s data in database

hi @edmaputra, could you please share how you did that? I’m looking into implementing the same thing

hi @alex88
What I’m doing is like this

UserModel userModel = session.users().getUserById(id, realm);
userModel.setSingleAttribute(LAST_LOGIN_TIME_KEY, String.valueOf(time));

where session is KeycloakSession. In my case, i set the last login time value on User’s Attribute.

Thanks, I’ll look into how to create a custom event listener first

@alex88 @edmaputra do you see a chance to open source your implementation?

Unfortunately I’ve never worked on it as there isn’t a very clear documentation on the subject

In the meantime I’ve implemented this: GitHub - ThoreKr/keycloak-last-login-event-listener: Automatically sets a last-login attribute on a user.

It updates also on token refresh which one might want to prevent, but in general it works sufficiently well.

Oh awesome thank you! I’ll check it out!

Thank you so much that helped me get what I wanted!

Does anyone know if it’s possible to have a listener “enabled” only for some realms? So I don’t update user attributes on all realms but only where I need to?
I know I can get the user realm from the sessions but I don’t want to hardcode it into the library

Update: Nvm just saw that you need to manually enable the event listener in the realm, neat!

Enable it on Realm level. In the left side menu, there are events options there you can add your custom event and enable it for your realm only.

thanks I saw that after seeing that the listener wasn’t being notified :slight_smile:


This is another repository from there you can get an idea for Keycloak event listener.

oh nice! plenty of extensions to look at!