how do i import the roles from an external idp into keycloak?

I would like to know if it is possible to explicitly import the roles from an external IDP into an internal one? Or if (and how) can I request a token in behalf to the user that would have that users’ roles from both the Central and SpringWeb Realm in the that token, without having to explicitly creating a Role Mapper for each user role.

Without explicitly creating a Role Mapper for each user role, the only solution that I have found was to extend the Keycloak code; which comes with obvious downsides.

In retrospect, it actually makes sense that Keycloak does not offer out-of-the-box a way of automatically importing all the roles from the external IDP. For instance, if I am using Google as an external IDP why should my internal IDP (i.e., Keycloak) care about the exact name of the roles used by Google?!. Most-likely, either those roles are meaningless for the internal IDP, and when they are meaningful they might have a different name. Regardless, for those exceptions, one can use the Role Mapper feature.

Nevertheless, to automatize a bit the process, I have created a file that maps the roles of the internal IDP to external IDP, for instance:


I also have a JSON file with a template of a Role Mapper example with some tags to be replaced afterwards (e.g., the fields role and external.role).

With scripts, I read the file that has the mapping between roles, and use Keycloak Admin REST API to create the roles, the mappers and so on.

The logic that I have used is as follows:

  • If the role does not exist in the external IDP I just skipped and assume that it was a mistake;
  • If the role does not exist in the internal IDP I create it as a Realm Role; For that, I use the endpoint POST /{realm}/roles
  • Finally, I create the Role Mapper using the endpoint POST /{realm}/identity-provider/instances/{alias}/mappers with the content of the JSON template Role Mapper file (with its tags replaced, accordingly).

The rationale for not creating the Realm Role in the external IDP is that all the roles from the external IDP should have been loaded already from the LDAP anyway. For the internal IDP, I do create because it is expectable that for mappings 1 to 1 that the roles from the LDAP (loaded into the external IDP) are not yet created on the internal IDP.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top