How to create a Script Mapper in Keycloak?

半腔热情 提交于 2019-12-09 03:15:19

问题


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);
  • Is this right? I made up user.getAttribute("myAttribute"). Is there a source of documentation where I can find how to get a Keycloak user attribute?
  • does the script need to return anything? Any help would be mostly welcome.

回答1:


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:

  • user: Source JavaDoc
  • realm: Source JavaDoc
  • token: Source JavaDoc
  • userSession: Source JavaDoc
  • keycloakSession: Source JavaDoc

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");

// 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!



来源:https://stackoverflow.com/questions/52518298/how-to-create-a-script-mapper-in-keycloak

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!