How to create a Script Mapper in Keycloak?

前端 未结 2 1540
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-14 12:22

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 documentati

相关标签:
2条回答
  • 2020-12-14 12:39

    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!

    0 讨论(0)
  • 2020-12-14 12:42

    I needed this feature but could not find this "script mapper" thing in my freshly installed 10.0.2. Turns out it is not enabled by default, as seen in the docs here : https://www.keycloak.org/docs/latest/server_installation/#profiles

    To enable it, you can either :

    • Create a file standalone/configuration/profile.properties with feature.scripts=enabled

    or

    • start the server with bin/standalone.sh|bat -Dkeycloak.profile.feature.scripts=enabled

    And it seems from the source code

    public boolean isSupported() {
        return Profile.isFeatureEnabled(Profile.Feature.SCRIPTS) && Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS);
    }
    

    that the upload_scripts should be enabled likewise

    I hope it will help someone

    0 讨论(0)
提交回复
热议问题