How to extend user roles from external source

Hi,

I would like to achieve the following behavior:

  • a user logs in
  • if the authentication is succesful, the keycloak roles are added.
  • in addition a REST-API is queried and additional roles are added to the user
  • these roles are included in the jwt tokens.

I first thought, I could use an SPI and use the UserLookupProvider interface. However, this does not seem to work. The Provider is visible under the “User Federation”-tab, but I don’t know how to enable the user lookup for all authentications for a given client.

Any ideas?

Thanks in advance,
Eike

Hey,

I am not sure it is possible to do it on connection. I would have think of an SPI as you did …

Maybe you can check for a specific mapper on client ?
Or you could add those roles as user attribute en map them in token with ‘UserAttribute’ roles.

This solution means that if roles changes you have to push info to keycloak base (using admin API)

Regards
Pj

i pretty much have same question, posted here Is there a way to convert saml assertion to token claims without storing them as role/group or user attribute

There is something called userSession mapper in saml/oidc identity provider mapper, and user session note mapper in client scopes… i am thinking of exploring that combination to check if it will work.

but , the time out (user session timeout), etc could be challenging… not sure if it will work.

Hi,

thanks for the ideas. I had a look at the mappers as well, but as far as I understand it, they would add one or more roles depending on the saml assertion - if the assertion contains X add Role A, B, C. My problem is, that I want to authenticate keycloak-internal users (and later on users based on SAML) and I need to call the external API in between to retrieve the roles for the corresponding user. And they might be very different for users with the same SAML assertions…

At the moment I do that within the client (Spring Boot application) but this is difficult to do, if multiple client apps are involved. It would be much easier, if I could add the roles “on-the-fly” in keycloak and adding them to the corresponding tokens.

@pjmalandrino:I also had the idea of synchronizing the user roles in keycloak with the one in the external system, but this seems to add a lot of overhead. And it get’s even more difficult, if the users are authenticated using SAML.

It would be great, if there were the possibility to add something like an interceptor. Or overwrite the default user provider…

I’ll have a look.
Again, thanks for the ideas :wink:

1 Like