Retrieve Identity Provider (Github) token

Hi,

Recently I have enabled Github as an identity provider to login through Keycloak. I am somehow trying to get access to the Github access_token that is stored in Keycloak after successful login by the user. This token is stored in FEDERATED_ENTITY table I have found out.

The use case that I have is the following: as soon as the user is registered in Keycloak with Github, I want to get the Github token and store it in my own MongoDB.

To monitor these events (EventType.REGISTER for example) I have created an SPI, using EventLIstenerProvider.

I have not found any type of documentation on how to do this exactly and in the best way and where I can grab this Github ‘access_token’ during registration and login events.

This has been bugging me for 3 days in a row now and I am really stuck. Does anyone know what is the best way forward on doing this. Any help would be really appreciated. Thanks in advance.

https://www.keycloak.org/docs/latest/server_admin/#retrieving-external-idp-tokens

This is not the scenario that I am looking for. Because this approach can only be done if User X is logged in, and through User X’ their own Keycloak Token I can retrieve that information.

This approach I cannot use from a custom event listener either I would think.

From an EventListener you can get it from the session. E.g.:

@Override
public void onEvent(Event event) {
    RealmModel realm = session.realms().getRealm(event.getRealmId());
    UserModel user = session.users().getUserById(realm, event.getUserId());
    String token = session.users().getFederatedIdentity​(realm, user, "github").getToken();
    // now do something with the token
}

Ahh that really helps, thanks a lot. I have been looking through some code like this. How do I obtain the session object here exactly? This is what I haven’t been able to figure out so far.

You are most likely using different versions of Keycloak when compiling and running. Make sure you have the same version both places.

That was exactly what was needed and did the trick. Thanks a lot for your help in getting this resolved, I really appreciate it!