keycloak-scim/authorization_services/topics/policy/js-policy.adoc

69 lines
2.3 KiB
Text
Raw Normal View History

2016-11-29 15:30:53 +00:00
[[_policy_js]]
=== JavaScript-Based Policy
2016-06-05 22:17:31 +00:00
You can use this type of policy to define conditions for your permissions using JavaScript. It is one of the rule-based policy types
2016-11-29 15:30:53 +00:00
supported by {{book.project.name}}, and provides flexibility to write any policy based on the <<fake/../evaluation-api.adoc#_policy_evaluation_api, Evaluation API>>.
2016-06-05 22:17:31 +00:00
To create a new JavaScript-based policy, select *JavaScript* in the dropdown list in the upper right corner of the permission listing.
.Add JavaScript Policy
2017-01-05 16:54:31 +00:00
image:../../{{book.images}}/policy/create-js.png[alt="Add JavaScript Policy"]
==== Configuration
2016-06-05 22:17:31 +00:00
* *Name*
+
A human-readable and unique string describing the policy. A best practice is to use names that are closely related to your business and security requirements, so you
can identify them more easily.
2016-06-05 22:17:31 +00:00
+
* *Description*
+
A string containing details about this policy.
2016-06-05 22:17:31 +00:00
+
* *Code*
+
The JavaScript code providing the conditions for this policy.
2016-06-05 22:17:31 +00:00
+
* *Logic*
+
2016-11-29 15:30:53 +00:00
The <<fake/../logic.adoc#_policy_logic, Logic>> of this policy to apply after the other conditions have been evaluated.
2016-06-05 22:17:31 +00:00
==== Examples
2016-06-05 22:17:31 +00:00
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
2016-06-05 22:17:31 +00:00
obtained from the execution context:
```javascript
var context = $evaluation.getContext();
var contextAttributes = context.getAttributes();
2016-06-29 22:51:16 +00:00
if (contextAttributes.containsValue('kc.client.network.ip_address', '127.0.0.1')) {
2016-06-05 22:17:31 +00:00
$evaluation.grant();
}
```
You can also use role-based access control (RBAC):
2016-06-05 22:17:31 +00:00
```javascript
var identity = $evaluation.getIdentity();
if (identity.hasRole('keycloak_user')) {
$evaluation.grant();
}
```
Or a combination of several 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();
}
```
2016-11-29 15:30:53 +00:00
When writing your own rules, keep in mind that the *$evaluation* object is an object implementing *org.keycloak.authorization.policy.evaluation.Evaluation*. For more information about what you can access from this interface, see the <<fake/../evaluation-api.adoc#_policy_evaluation_api, Evaluation API>>.