Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Keycloak provides a feature called "Policy Script" where claims can be pushed to policies based on regular expressions using JavaScript. The Policy Script allows for custom validation of a policy request before it is granted or denied.

To use regular expressions in Policy Script:

  1. Go to the Keycloak admin console and select the realm you want to configure.
  2. Click on "Clients" in the left-hand menu and select the client that you want to configure.
  3. Click on "Authorization" in the client settings menu.
  4. Under "Policy" click "Add policy".
  5. In the "Add policy" screen, select "Script" as the policy type.
  6. In the "Script" field, write the JavaScript code that will check for the regular expression pattern that matches the claim you want to push to the policy.
  7. Use the following code snippet to evaluate a regular expression:
var regex = new RegExp('your-regular-expression');
if (regex.test(claim-value)) {
  // Add the claim to the policy
  policy.addClaim('your-claim-name', 'your-claim-value');
}
  1. In the "Apply Policy to" field, select the resources, scopes, and/or roles to which the policy should be applied.
  2. Click "Save" to create the policy.

Now, when a user tries to access a resource that requires the policy, Keycloak will execute the Policy Script and add the claim to the policy if the regular expression matches the claim value.