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
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.
Now this info will start coming in your access token:
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]
This is how I could eventually map group attributes (inherited as user attributes, as suspected before) into user informations, into the "other claims" section :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With