How to create JS policy

I want to write a js policy for authorization.
I have enabled scripts feature while running docker, you can see scripts are enabled.

 docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin -e KC_FEATURES=scripts quay.io/keycloak/keycloak start-dev

Unable to find image 'quay.io/keycloak/keycloak:latest' locally
latest: Pulling from keycloak/keycloak
cdcdf07a5ffb: Pull complete 
f2c93bceae08: Pull complete 
70dc8bfde2cc: Pull complete 
540ad3fc32e5: Pull complete 
Digest: sha256:8ebb3930c41e8a066c4246eaf351ac09cdc984e11b1f607d6ff4ce10d69dc808
Status: Downloaded newer image for quay.io/keycloak/keycloak:latest
Updating the configuration and installing your custom providers, if any. Please wait.
2023-06-22 05:21:48,549 INFO  [org.keycloak.common.Profile] (main) Preview features enabled: scripts
2023-06-22 05:21:53,148 INFO  [io.quarkus.deployment.QuarkusAugmentor] (main) Quarkus augmentation completed in 4817ms
2023-06-22 05:21:53,725 INFO  [org.keycloak.common.Profile] (main) Preview features enabled: scripts
2023-06-22 05:21:54,006 INFO  [org.keycloak.quarkus.runtime.hostname.DefaultHostnameProvider] (main) Hostname settings: Base URL: <unset>, Hostname: <request>, Strict HTTPS: false, Path: <request>, Strict BackChannel: false, Admin URL: <unset>, Admin: <request>, Port: -1, Proxied: false

But I am not able to see js type in this


So how to create js policy?

Hi,
To develop the policy, you need to follow this project structure:

First, refer to the following official doc:

For example, in the folder script-example-policy you should have the following files:

META-INF/keycloak-scripts.json
script-example-policy.js

The META-INF/keycloak-scripts.json define the policies as follows:

{
    "policies": [
        {
            "name": "Example Authz Policy",
            "fileName": "script-example-policy.js",
            "description": "Example Authz Policy"
        }
    ]
}

The script-example-policy.js in this example only users with the “admin” role are allowed:

var identity = $evaluation.getContext().getIdentity()
LOG.info("evaluating policy " + script.name + " for: " + identity.getId());

if (identity.hasRole("admin")) {
  $evaluation.grant();
}

Next, generate the JAR file and deploy it to the server in the folder /opt/keycloak/providers. For example:

jar cvf script-example-policy.jar -C script-example-policy .

Finally, after deploying the JAR file, you should be able to see the policy in Keycloak.

Regards,