Keycloak/OIDC : retrieve user groups attributes

Thomas Escolan picture Thomas Escolan · May 29, 2019 · Viewed 9k times · Source

I've extracted a user's groups information from the OIDC endpoint of Keycloak, but they don't come with the group ATTRIBUTES I defined (see Attributes tab into the group form, near Settings). Is there a claim to add to my request?

I'm using a RESTeasy client to reach Keycloak's admin API (had much better results than using the provided admin client, yet):

@Path("/admin/realms/{realm}")
public interface KeycloakAdminService {
    @GET
    @Path("/users/{id}/groups")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    List<GroupRepresentation> getUserGroups(@PathParam("realm") String realm, @PathParam("id") String userId,
                                            @HeaderParam(AUTHORIZATION) String accessToken);
    //DEBUG the access token must always be prefixed by "Bearer "
}

So I can fetch a user's groups:

private void fetchUserGroups(UserInfoOIDC infos, String userId) {
    log.info("Fetching user groups from {}...", getRealm());
    try {
        KeycloakAdminService proxy = kcTarget.proxy(KeycloakAdminService.class);
        AccessTokenResponse response = authzClient.obtainAccessToken(getAdminUsername(), getAdminPassword());
        List<GroupRepresentation> groups = proxy.getUserGroups(getRealm(), userId,
                "Bearer " + response.getToken());
        infos.importUserGroups(groups); //DEBUG here we go!
    } catch (WebApplicationException e) {
        log.error("User groups failure on {}: {}", getRealm(), e.getMessage());
    }
}

But when it comes to data exploration, it turns out that no attributes are provided into the GroupRepresentation#getAttributes structure.

I've read that claims can be added to user info requests. Does it work on the admin API? How can I achieve that result with RESTeasy templates? Thx

Answer

tryingToLearn picture tryingToLearn · May 30, 2019

I was able to achieve this by adding groups/roles info in token other claims property:

For this in keycloak config, go to your client -> mappers & add a group/role mapper. E.g.

enter image description here

Now this info will start coming in your access token:

enter image description here

To access these group attribute in Java you can extract it from otherclaims property of accesstoken. E.g.:

KeycloakSecurityContext keycloakSecurityContext = (KeycloakSecurityContext)(request.getAttribute(KeycloakSecurityContext.class.getName()));         
AccesToken token = keycloakSecurityContext.getToken();

In below image you can see that otherclaims property of token is filled with groups attribute that we created on keycloak. Note that if we had named "token claim property" as groupXYZ, the otherclaims would be showing: groupsXYZ=[Administrator]

enter image description here