Granting roles from federated user SPI - mapping to token

Hi,
I’m stuck getting roles into tokens.
My users come from a federated user storage SPI which works fine.
In the KC SPI implementation I locate the client roles I need to grant and call AbstractInMemoryUserAdapter.grantRole(..)

However, I seemingly cannot get these roles into the token.

In fact, I can’t get any roles into the token.

On an older project I used KC 3.X and this worked fine. On this new project I can’t find a way to expose roles to JWT tokens.

Thanks for any pointers.
Rob

I am not sure that you are able to do that, since your user is just mapped form Federation and you want to add some role that is not exist in Keycloak itself.
What you can do is to update endpoint in your Service for getting user and to retrieve roles.
Then map roles in Keycloak User that you have created:

public class CCUser extends AbstractUserAdapter {

    public static final String ROLES = "roles";

    @Getter
    private List<CCRole> roles;

   @Override
      public List<String> getAttribute(String name) {
  
          if (ROLES.equals(name))
              return List.of(String.valueOf(roles));
  }

  @Override
      public Map<String, List<String>> getAttributes() {
          MultivaluedHashMap<String, String> attributes = new MultivaluedHashMap<>();
  
          getGroupsFromRoles()
                  .forEach(group -> attributes.add(GROUPS, group));
  
          return attributes;
      }

Then create mapper that will map attribute ‘roles’ from user and set it to multi value:

You can map roles in your UserAdapter implementation, like here: keycloak-extensions-demo/flintstones-userprovider/src/main/java/dasniko/keycloak/user/flintstones/FlintstoneUserAdapter.java at 1427dfbea8e74d8eb74ed0266aa7802e07728c96 · dasniko/keycloak-extensions-demo · GitHub

I’m mapping roles that doesn’t exist in Keyclaok as a resource, but I can map them to the token with regular role mappers, not need to do anything extra.