68 lines
2.2 KiB
Text
68 lines
2.2 KiB
Text
== JavaScript-Based Policy
|
|
|
|
This type of policy allows you to define conditions for your permissions using JavaScript. It is one of the _Rule-Based_ policy types
|
|
supported by {{book.project.name}}, providing lot of flexibility to write any policy based on the link:evaluation-api.adoc[Evaluation API].
|
|
|
|
To create a new policy select the option *JavaScript* in the dropdown located in the right upper corner of the permission listing.
|
|
|
|
.Add JavaScript Policy
|
|
image:../../images/policy/create-js.png[alt="Add JavaScript Policy"]
|
|
|
|
=== Configuration
|
|
|
|
* *Name*
|
|
+
|
|
A human-readable and unique string describing the policy. We strongly suggest you to use names that are closely related with your business and security requirements, so you
|
|
can identify them more easily and also know what they actually mean
|
|
+
|
|
* *Description*
|
|
+
|
|
A string with more details about this policy
|
|
+
|
|
* *Code*
|
|
+
|
|
The JavaScript code providing the conditions for this policy
|
|
+
|
|
* *Logic*
|
|
+
|
|
The link:logic.html[logic] of this policy
|
|
|
|
=== Examples
|
|
|
|
Here is a simple example of a JavaScript-Based policy that uses Attribute-Based Access Control (ABAC) to define a condition based on an attribute
|
|
obtained from the execution context:
|
|
|
|
```javascript
|
|
var context = $evaluation.getContext();
|
|
var contextAttributes = context.getAttributes();
|
|
|
|
if (contextAttributes.containsValue('kc.client.network.ip_address', '127.0.0.1')) {
|
|
$evaluation.grant();
|
|
}
|
|
```
|
|
|
|
You can even use RBAC if you want to:
|
|
|
|
```javascript
|
|
var identity = $evaluation.getIdentity();
|
|
|
|
if (identity.hasRole('keycloak_user')) {
|
|
$evaluation.grant();
|
|
}
|
|
```
|
|
|
|
Or even a mix of different access control mechanisms:
|
|
|
|
```javascript
|
|
var context = $evaluation.getContext();
|
|
var identity = context.getIdentity();
|
|
var attributes = identity.getAttributes();
|
|
var email = attributes.getValue('email').asString(0);
|
|
|
|
if (identity.hasRole('admin') || email.endsWith('@keycloak.org')) {
|
|
$evaluation.grant();
|
|
}
|
|
```
|
|
|
|
When writing your own rules, keep in mind that the *$evaluation* object is just a object implementing *org.keycloak.authorization.policy.evaluation.Evaluation*. For more details about what you can access from this interface,
|
|
please take a look at link::/policy/evaluation-api.adoc[Evaluation API].
|