I need to create a Protocol Mapper of type Script Mapper in Keycloak. The script should get a user attribute, check its size, and put it on the token. I found no documentation or examples of how a script should be created. From the bits and pieces I could gather, I guess I the script would need to look something like:
var value = user.getAttribute("myAttribute");
if (value.length > LIMIT) {
value = value.substring(0,LIMIT);
}
token.setOtherClaims("myAttribute",value);
User property protocol mappers allow you to map built in properties defined on the Keycloak user interface to a claim in a token. Protocol mappers can be defined for a single client, or they can be defined for a client scope which can be shared between multiple different clients.
The magic of Script Mappers can be understood by looking at the keycloak sources here: Source
The script can return something by using the exports variable like this
exports = "Claim Value"
The different types:
Here is an example script:
// you can set standard fields in token
token.setAcr("test value");
// you can set claims in the token
token.getOtherClaims().put("claimName", "claim value");
// multi-valued claim (thanks to @ErwinRooijakkers)
token.getOtherClaims().put('foo', Java.to(['bars'], "java.lang.String[]"))
// work with variables and return multivalued token value
var ArrayList = Java.type("java.util.ArrayList");
var roles = new ArrayList();
var client = keycloakSession.getContext().getClient();
var forEach = Array.prototype.forEach;
forEach.call(user.getClientRoleMappings(client).toArray(), function(roleModel) {
roles.add(roleModel.getName());
});
exports = roles;
Hope it helps!
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