Sanitize Keycloak user group names in a Javascript Mapper


in Keycloak we have groups with special characters that are not supported by the client.
We decided to sanitize the group names in a Javascript Mapper, but we are not able to return the new groups array correctly.

Here is the resulting SAML response:

"groups":["[object Array]"]

The desired response:

"groups":["group1", "group2", ...]

And the mapper code:

var groups = [];
var baseGroups = user.getGroups().toArray();

for (var i=0; i<user.getGroupsCount(); i++) {
    groups.push(baseGroups[i].getName().replace(/[^a-zA-Z ôéèêà]/g, '').trim());


Do you have any idea how to obtain the result we want ?


I had a similar problem using a JavaScript mapper serializing oidc claims (to JSON). I solved it by copying the JavaScript array contents to a plain Java Array and returning this instead of the intermediate JavaScript array. You could try to add this to your code (after the sanitizing, but before returning the groups object):

var resultJArray = java.lang.reflect.Array.newInstance(java.lang.String.class, groups.length);
for (var j = 0; j < groups.length; j++) {
	resultJArray[j] = groups[j];

//one of them might work
token.setOtherClaims("groups", resultJArray);
return groups;


Thank you so much ! It works ! :slightly_smiling_face: