Scripting a Policy Condition

You can use scripts to tailor the actions AM does as part of policy evaluation to your environment.

AM includes a sample policy condition script that demonstrates how to access a user's profile information, use that information in HTTP calls, and make a policy decision based on the outcome.

To examine the contents of the sample policy condition script in the AM console, navigate to Realms > Top Level Realm > Scripts, and then select Scripted Policy Condition.

Related information:

Preparing AM to use Scripted Policy Conditions

AM requires a small amount of configuration before trying the default policy condition script. The default policy condition script requires that the subject of the policy has an address in their profile. The script compares the address to the country in the resource URL and to the country from which the request originated, as determined by an external GeoIP web service. The demo user also requires access to evaluate policies.

Tasks:

To Add an Address to the Demo User

In this procedure, add an address value to the demo user's profile. The default policy condition script uses the address when performing policy evaluation.

  1. Log in as an AM administrator, for example amAdmin.

  2. Select Realms > Top Level Realm > Identities.

  3. On the Identities tab, select the demo user.

  4. In Home Address, enter a valid address. For example:

    201 Mission St, Suite 2900, San Francisco, CA 94105
  5. Select Save Changes.

To Allow a User to Evaluate Policies

In this procedure, add a user to a group and assign the privilege required to perform policy evaluations.

  1. Log in as an AM administrator, for example amAdmin.

  2. Select Realms > Top Level Realm > Identities.

  3. Select Add Identity, enter an ID for the identity, such as restPolicyUser, complete the required fields, and then select Create.

  4. Return to Realms > Top Level Realm > Identities. On the Groups tab, select Add Group, enter an ID for the group, such as policyEval, and then select Create.

  5. Return to Realms > Top Level Realm > Identities.

    1. Select the user you created, for example, restPolicyUser.

    2. Select the Groups tab.

    3. In the Name box, select the group created in step 4, for example policyEval.

    4. Select Save Changes.

  6. Select Realms > Top Level Realm > Identities > Groups.

  7. Select the group created in step 4, for example policyEval.

  8. On the Privileges tab, select Policy Admin.

  9. Select Save Changes.

To Create a Policy that Uses the Default Policy Condition Script

In this procedure, create a policy that uses the default policy condition script. Policy evaluations can then be performed to test the script functionality.

  1. Log in as an AM administrator, for example amAdmin.

  2. Select Realms > Top Level Realm > Authorization > Policy Sets.

  3. On the Policy Sets page, select Default Policy Set.

  4. On the Default Policy Set page, select Add a Policy.

  5. Define the policy as follows:

    1. Enter a name for the policy.

    2. Define resources to which the policy applies:

      1. Select URL from the Resource Type drop down list.

      2. Select the resource pattern *://*:*/* from the Resources drop down list.

      3. Select Add.

        The *://*:*/* resource appears in the Resources field.

      4. Select Add Resource to add a second resource to the policy.

      5. Select the resource pattern *://*:*/*?* from the Resources drop down list.

      6. Select Add.

        The *://*:*/*?* resource appears along with the *://*:*/* resource in the Resources field.

      7. Select Create to create the policy.

        The Resources tab appears as follows:

        Resources for an example policy that uses the default policy condition script.
    3. Specify actions to which the policy applies:

      1. Select the Actions tab.

      2. Select GET from the Add an Action drop down list.

      3. The GET action appears in the list of actions. The default state for the GET action is Allow.

        The Actions tab appears as follows:

        Actions for an example policy that uses the default policy condition script.
      4. Select Save Changes.

    4. Configure identities to which the policy applies:

      1. Select the Subjects tab.

      2. Select the edit icon—the pencil.

      3. Select Authenticated Users from the Type drop down list.

      4. Select the OK icon—the check mark.

        The Subjects tab appears as follows:

        Subjects for an example policy that uses the default policy condition script.
      5. Select Save Changes.

    5. Configure environments in which the policy applies:

      1. Select the Environments tab.

      2. Select Add an Environment Condition.

      3. Select Script from the Type drop down list.

      4. Select Scripted Policy Condition from the Script Name drop down list.

      5. Select the OK icon—the check mark.

        The Environments tab appears as follows:

        Environments for an example policy that uses the default policy condition script.
      6. Select Save Changes.

    6. No additional configuration is required in the Response Attributes or Details tabs.

To Enable Debug Logging for Scripted Policy Conditions

This procedure shows how to enable trace-level debug logging for scripted policy conditions, so that logger output from the default policy condition script is recorded.

  1. Ensure that the script containing the debug output you want to capture has executed at least once to create the logger.

    The name of the scripted policy decision logger has the format: scripts.POLICY_CONDITION.script-UUID.

  2. Log in as the AM administrator, amAdmin.

  3. Go to the Logback.jsp page, for example: https://openam.example.com:8443/openam/Logback.jsp.

  4. In the Logger list, scroll to select the scripted policy decision logger; for example scripts.POLICY_CONDITION.9de3eb62-f131-4fac-a294-7bd170fd4acb.

  5. From the Level list, choose the debug level required. In this example, select Trace.

  6. Click Apply.

    Enabling debug logging for a scripted conditions.

    Trace-level debug logging is now enabled for scripted policy conditions, with script output appearing in the /path/to/openam/var/debug/Policy debug log file.

    Changes made in the Logback.jsp page are not persisted after rebooting AM or the container in which it runs.

    For more information on configuring debug logging, see Debug Logging.

Trying the Default Policy Condition Script

To evaluate against a policy, you must first obtain an SSO token for the subject performing the evaluation, in this case the demo user. You can then make a call to the policies?_action=evaluate endpoint, including some environment information, which the policy uses to make an authorization decision.

To Evaluate a Policy
  1. Obtain an SSO token for the demo user:

    $ curl \
    --request POST \
    --header "Content-Type: application/json" \
    --header "X-OpenAM-Username: demo" \
    --header "X-OpenAM-Password: Ch4ng31t" \
    --header "Accept-API-Version: resource=2.0, protocol=1.0" \
    'https://openam.example.com:8443/openam/json/realms/root/realms/alpha/authenticate'
    {
        "tokenId":"AQIC5wM...TU3OQ*",
        "successUrl":"/openam/console",
        "realm":"/alpha"
    }
  2. Obtain an SSO token for the user who has the privilege required to evaluate policies. For example, restPolicyUser.

    $ curl \
    --request POST \
    --header "Content-Type: application/json" \
    --header "X-OpenAM-Username: restPolicyUser" \
    --header "X-OpenAM-Password: myStrongPassword" \
    --header "Accept-API-Version: resource=2.0, protocol=1.0" \
    'https://openam.example.com:8443/openam/json/realms/root/realms/alpha/authenticate'
    {
        "tokenId":"AQIC8aF...TA1OQ*",
        "successUrl":"/openam/console",
        "realm":"/alpha"
    }
  3. Send an evaluation request to the policies endpoint, providing the SSO token of the restPolicyUser user as the value of the iPlanetDirectoryPro header.

    In the JSON data, set the subject object to the SSO token of the demo user. In the resources object, include a URL that resides on a server in the same country as the address set for the demo user. In the environment object, include an IP address that is also based in the same country as the user and the resource.

    The example below uses the URL of a web site and an IP address located in the United States:

    $ curl \
    --request POST \
    --header "Content-Type: application/json" \
    --header "iPlanetDirectoryPro: AQIC8aF...TA1OQ*" \
    --data '{
        "resources":[
            "https://www.us-site.com:8443/index.html"
        ],
        "application":"iPlanetAMWebAgentService",
        "subject":{
            "ssoToken":"AQIC5wM...TU3OQ*"
        },
        "environment":{
            "IP":[
                "38.99.39.210"
            ]
        }
    }' \
    "https://openam.example.com:8443/openam/json/realms/root/policies?_action=evaluate"
    {
        "advices":{},
        "ttl":9223372036854775807,
        "resource":"https://www.us-site.com:8443/index.html",
        "actions":{
            "POST":true,
            "GET":true
        },
        "attributes":{
            "countryOfOrigin":[
                "United States"
            ]
        }
    }

    If the country in the subject's profile matches the country determined from the source IP in the environment and the country determined from the resource URL, then AM returns a list of actions available. The script will also add an attribute to the response called countryOfOrigin with the country as the value.

    If the countries do not match, no actions are returned. In the following example, the resource URL is based in France, while the IP and user's address in the profile are based in the United States:

    $ curl \
    --request POST \
    --header "Content-Type: application/json" \
    --header "iPlanetDirectoryPro: AQIC8aF...TA1OQ*" \
    --data '{
        "resources":[
            "https://www.france-site.com:8443/index.html"
        ],
        "application":"iPlanetAMWebAgentService",
        "subject":{
            "ssoToken":"AQIC5wM...TU3OQ*"
        },
        "environment":{
            "IP":[
                "38.99.39.210"
            ]
        }
    }' \
    "https://openam.example.com:8443/openam/json/realms/root/policies?_action=evaluate"
    {
        "advices": {},
        "ttl": 9223372036854775807,
        "resource": "https://www.france-site.com:8443/index.html",
        "actions": {},
        "attributes": {}
    }

Policy Condition Script API Functionality

In addition to the functionality provided by "Accessing HTTP Services" and "Debug Logging", scripted policy condition scripts can access the authorization state of a request, the information pertaining a session, and the user profile's data.

This information can then be returned as needed in the response to an authorization request.

Important

If you use static methods within policy scripts, you must whitelist those scripts. Otherwise, policy evaluation will fail with an exception (logged in the Entitlement debug file) similar to the following:

java.lang.SecurityException: Access to Java class script-name is prohibited.

Accessing Authorization State

Server-side scripts can access the current authorization state through the following objects:

Authorization State Objects
ObjectTypeDescription

authorized

Boolean

Return true if the authorization is currently successful, or false if authorization has failed. Server-side scripts must set a value for authorized before completing.

environment

Map<String, Set<String>>

Describe the environment passed from the client making the authorization request.

For example, the following shows a simple environment map with a single entry:

"environment": {
    "IP": [
        "127.0.0.1"
    ]
}

resourceURI

String

Specify the URI of the resource to which authorization is being requested.

username

String

Specify the user ID of the subject that is requesting authorization.


Accessing Profile Data

Server-side authorization scripts can access profile data of the subject of the authorization request through the methods of the identity object.

Note

To access the profile data of the subject, they must be logged in and their SSO token must be available.

Authorization Script Profile Data Methods
MethodParametersReturn TypeDescription

identity.getAttribute

Attribute Name (type: String)

Set

Return the values of the named attribute for the subject of the authorization request.

identity.setAttribute

Attribute Name (type: String)

Attribute Values (type: Array)

Void

Set the named attribute to the values specified by the attribute value for the subject of the authorization request.

identity.addAttribute

Attribute Name (type: String)

Attribute Value (type: String)

Void

Add an attribute value to the list of attribute values associated with the attribute name for the subject of the authorization request.

identity.store

None

Void

Commit any changes to the identity repository.

Caution

You must call store() otherwise changes will be lost when the script completes.


Accessing Session Data

Server-side authorization scripts can access session data of the subject of the authorization request through the methods of the session object.

Note

To access the session data of the subject, they must be logged in and their SSO token must be available.

Authorization Script Session Methods
MethodParametersReturn TypeDescription

session.getProperty

Property Name (type: String)

String

Retrieve properties from the session associated with the subject of the authorization request. See the table below for example properties and their values.


The following table demonstrates some of the session properties available to the session.getProperty() method, and example values:

Get Session Data Example Keys and Values
KeySample value
AMCtxIde370cca2-02d6-41f9-a244-2b107206bd2a-122934
amlbcookie01
authInstant2018-04-04T09:19:05Z
AuthLevel0
CharSetUTF-8
clientTypegenericHTML
FullLoginURL/openam/XUI/?realm=alpha#login/
Host198.51.100.1
HostNameopenam.example.com
Localeen_US
Organizationdc=openam,dc=forgerock,dc=org
Principaluid=amAdmin,ou=People,dc=openam,dc=forgerock,dc=org
PrincipalsamAdmin
ServiceldapService
successURL/openam/console
sun.am.UniversalIdentifieruid=amAdmin,ou=People,dc=openam,dc=forgerock,dc=org
UserIdamAdmin
UserProfileRequired
UserTokenamAdmin
webhooksmyWebHook

Setting Authorization Responses

Server-side authorization scripts can return information in the response to an authorization request.

Authorization Script Response Methods
MethodParametersReturn TypeDescription

responseAttributes.put

Attribute Name (type: String)

Attribute Values (type: Array)

Void

Add an attribute to the response to the authorization request.

advice.put

Advice Key (type: String)

Advice Values (type: Array)

Void

Add advice key-value pairs to the response to a failing authorization request.

ttl

TTL Value (type: Integer)

Void

Add a time-to-live value, which is a timestamp in milliseconds to the response to a successful authorization. After the time-to-live value the decision is no longer valid.

If no value is set, TTL Value defaults to Long.MAX_VALUE (9223372036854775807), which means the decision has no timeout, and can live for as long as the calling client holds on to it. In the case of policy enforcement points, they hold onto the decision for their configured cache timeout.


Read a different version of :