Guide to working with authorization. ForgeRock Access Management provides authentication, authorization, entitlement and federation software.

Preface

This guide covers concepts, implementation procedures, and customization techniques for working with the authorization features of AM.

This guide is written for anyone using AM to manage authorization.

About ForgeRock Identity Platform™ Software

ForgeRock Identity Platform™ serves as the basis for our simple and comprehensive Identity and Access Management solution. We help our customers deepen their relationships with their customers, and improve the productivity and connectivity of their employees and partners. For more information about ForgeRock and about the platform, see https://www.forgerock.com.

Chapter 1. Introducing Authorization

This chapter provides an overview of authorization.

OpenAM provides access management, which consists of:

  • Authentication: determining who is trying to access a resource

  • Authorization: determining whether to grant or deny access to the resource

Whether access is granted depends on what the policies about access are, who is trying to gain access, and perhaps some other conditions, such as whether the access itself needs to happen over a secure channel or what time of day it is.

1.1. Resource Types, Policy Sets, and Policies

Define authorization policies to allow OpenAM to determine whether to grant a subject access to a resource.

A policy defines the following:

resources

The resource definitions constrain which resources, such as web pages or access to the boarding area, the policy applies to.

actions

The actions are verbs that describe what the policy allows users to do to the resources, such as read a web page, submit a web form, or access the boarding area.

subject conditions

The subject conditions constrain who the policy applies to, such as all authenticated users, only administrators, or only passengers with valid tickets for planes leaving soon.

environment conditions

The environment conditions set the circumstances under which the policy applies, such as only during work hours, only when accessing from a specific IP address, or only when the flight is scheduled to leave within the next four hours.

response attributes

The response attributes define information that OpenAM attaches to a response following a policy decision, such as a name, email address, or frequent flyer status.

When queried about whether to let a user through to a protected resource, OpenAM decides whether to authorize access or not based on applicable policies as described below in "Policy Decisions". OpenAM communicates its decision to the application that is using OpenAM for access management. In the common case, this is a policy agent installed on the server where the application runs. The agent then enforces the authorization decision from OpenAM.

Relationship between Realms, Policies, and Policy Sets
Shows the relationship between realms, policies, and resource types.

To help with the creation of policies, OpenAM uses resource types and policy sets.

Resource types

Resource types define a template for the resources that policies apply to, and the actions that could be performed on those resources.

For example, the URL resource type that is included by default in OpenAM acts as a template for protecting web pages or applications. It contains resource patterns, such as *://*:*/*?*, which can be made more specific when used in the policy. The actions that the resource supports are also defined, as follows:

  • GET

  • POST

  • PUT

  • HEAD

  • PATCH

  • DELETE

  • OPTIONS

OpenAM also includes a resource type to protect REST endpoints, with patterns including https://*:*/*?* and the CRUDPAQ actions:

  • CREATE

  • READ

  • UPDATE

  • DELETE

  • PATCH

  • ACTION

  • QUERY

Policy Sets

Policy Sets are associated with a set of resource types, and contain one or more policies based upon the template it provides.

For example, an application for Example.com's HR service might contain resource types that constrain all policies to apply to URL resource types under http*://example.com/hr* and http*://example.com/hr*?*, and only the HTTP GET and POST actions.

Configure policy sets, policies, and resource types in the OpenAM console under Realms > Realm Name > Authorization.

Policy Sets in the AM Console
Authorization options in the AM console.

For more information on viewing, creating, and editing policies and resource types, see "Configuring Resource Types, Policy Sets, and Policies".

1.2. Policy Decisions

OpenAM relies on policies to reach authorization decisions, such as whether to grant or to deny access to a resource. OpenAM acts as the policy decision point (PDP), whereas OpenAM policy agents act as policy enforcement points (PEP). In other words, a policy agent or other PEP takes responsibility only for enforcing a policy decision rendered by OpenAM. When you configured applications and their policies in OpenAM, you used OpenAM as a policy administration point (PAP).

Concretely speaking, when a PEP requests a policy decision from OpenAM it specifies the target resource(s), the policy set (default: iPlanetAMWebAgentService), and information about the subject and the environment. OpenAM as the PDP retrieves policies within the specified policy set that apply to the target resource(s). OpenAM then evaluates those policies to make a decision based on the conditions matching those of the subject and environment. When multiple policies apply for a particular resource, the default logic for combining decisions is that the first evaluation resulting in a decision to deny access takes precedence over all other evaluations. OpenAM only allows access if all applicable policies evaluate to a decision to allow access.

OpenAM communicates the policy decision to the PEP. The concrete decision, applying policy for a subject under the specified conditions, is called an entitlement.

The entitlement indicates the resource(s) it applies to, the actions permitted and denied for each resource, and optionally response attributes and advice.

When OpenAM denies a request due to a failed condition, OpenAM can send advice to the PEP, and the PEP can then take remedial action. For instance, suppose a user comes to a web site having authenticated with an email address and password, which is configured as authentication level 0. Had the user authenticated using a one-time password, the user would have had authentication level 1 in their session. Yet, because they have authentication level 0, they currently cannot access the desired page, as the policy governing access requires authentication level 1. OpenAM sends advice, prompting the PEP to have the user re-authenticate using a one-time password module, gaining authentication level 1, and thus having OpenAM grant access to the protected page.

1.3. Example Authorization

Consider the case where OpenAM protects a user profile web page. An OpenAM policy agent installed in the web server intercepts client requests to enforce policy. The policy says that only authenticated users can access the page to view and to update their profiles.

When a user browses to the profile page, the OpenAM policy agent intercepts the request. The policy agent notices that the request is to access a protected resource, but the request is coming from a user who has not yet logged in and consequently has no authorization to visit the page. The policy agent therefore redirects the user's browser to OpenAM to authenticate.

OpenAM receives the redirected user, serving a login page that collects the user's email and password. With the email and password credentials, OpenAM authenticates the user, and creates a session for the user. OpenAM then redirects the user to the policy agent, which gets the policy decision from OpenAM for the page to access, and grants access to the page.

While the user has a valid session with OpenAM, the user can go away to another page in the browser, come back to the profile page, and gain access without having to enter their email and password again.

Notice how OpenAM and the policy agent handle the access in the example. The web site developer can offer a profile page, but the web site developer never has to manage login, or handle who can access a page. As OpenAM administrator, you can change authentication and authorization independently of updates to the web site. You might need to agree with web site developers on how OpenAM identifies users so web developers can identify users by their own names when they log in. By using OpenAM and policy agents for authentication and authorization, your organization no longer needs to update web applications when you want to add external access to your Intranet for roaming users, open some of your sites to partners, only let managers access certain pages of your HR web site, or allow users already logged in to their desktops to visit protected sites without having to type their credentials again.

1.4. Reaching Policy Decisions

OpenAM has to match policies to resources to take policy decisions. For a policy to match, the resource has to match one of the resource patterns defined in the policy. The user making the request has to match a subject. Furthermore, at least one condition for each condition type has to be satisfied.

If more than one policy matches, OpenAM has to reconcile differences. When multiple policies match, the order in which OpenAM uses them to make a policy decision is not deterministic. However, a deny decision overrides an allow decision, and so by default once OpenAM reaches a deny decision it stops checking further policies. If you want OpenAM to continue checking despite the deny, navigate to Configure > Global Services, click Policy Configuration, and then enable Continue Evaluation on Deny Decision.

Chapter 2. Implementing Authorization

This chapter covers how to implement authorization using the AM console and the REST API.

2.1. Implementing Authorization Using the AM Console

This section covers the following topics:

2.1.1. Configuring Resource Types, Policy Sets, and Policies

You can configure resource types, policy sets, and policies by using the AM console, or by using the REST interface.

This section explains how to use the AM console to configure resource types, policy sets, and policies to protect resources.

For information on managing resource types, policy sets, and policies by using the REST API, see "Managing Resource Types", "Managing Policy Sets", and "Managing Policies".

Tip

You can also configure policy sets and policies by using the ssoadm command. For more information see ssoadm(1) in the Reference.

2.1.1.1. Configuring Resource Types

This section describes the process of using the OpenAM console for creating resource types, which define a template for the resources that policies apply to, and the actions that could be performed on those resources.

To Configure a Resource Type by Using the AM Console
  1. In the AM console, select Realms > Realm Name > Authorization > Resource Types.

    1. To create a new resource type, click New Resource Type.

    2. To modify an existing resource type, click the resource type name.

    3. To delete an existing resource type, in the row containing the resource type click the Delete button.

      You can only delete resource types that are not being used by policy sets or policies. Trying to delete a resource type that is in use returns an HTTP 409 Conflict status code.

      Remove the resource type from any associated policy sets or policies to be able to delete it.

  2. Provide a name for the resource type, and optionally a description.

    Do not use special characters within resource type, policy, or policy set names (for example, "my+resource+type") when using the AM console or REST endpoints. Using the special characters listed below causes OpenAM to return a 400 Bad Request error. The special characters are: double quotes ("), plus sign (+), comma (,), less than (<), equals (=), greater than (>), backslash (\), forward slash (/), semicolon (;), and null (\u0000).

  3. To define resource patterns that policies using this resource type can expand upon, follow the steps below:

    1. In the Add a new pattern box, enter a pattern with optional wildcards that the policies will use as a template.

      For information on specifying patterns for matching resources, see "Specifying Resource Patterns with Wildcards".

    2. Click the Add Pattern button to confirm the pattern.

    Tip

    To remove a pattern, click the Delete icon.

  4. To define the actions that policies using this resource type can allow or deny, follow the steps below:

    1. In the Add a new action box, enter an action related to the types of resources being described, and then click Add Action.

    2. Select either allow or deny as the default state for the action.

    To remove an action, click the Delete icon.

  5. Continue adding the patterns and actions that your resource type requires.

    Configuring Resource Types in the AM Console
    Configuring resource types in the AM console.

  6. Click Create Resource Type to save a new resource type or Save Changes to save modifications to an existing resource type.

2.1.1.2. Configuring Policy Sets

This section describes how to use the OpenAM console to create policy sets, which are used as templates for policies protecting Web sites, Web applications, or other resources.

To Configure a Policy Set Using the AM Console
  1. In the AM console, select Realms > Realm Name > Authorization > Policy Sets.

    1. To create a new policy set, click New Policy Set.

    2. To modify an existing policy set, in the row containing the name of the policy set click the Edit icon, and then click the Settings tab.

  2. Enter an ID for the policy set. This is a required parameter.

  3. Enter a name for the policy set. The name is optional and is for display purposes only.

    Do not use special characters within resource type, policy, or policy set names (for example, "my+resource+type") when using the AM console or REST endpoints. Using the special characters listed below causes OpenAM to return a 400 Bad Request error. The special characters are: double quotes ("), plus sign (+), comma (,), less than (<), equals (=), greater than (>), backslash (\), forward slash (/), semicolon (;), and null (\u0000).

  4. In the Resource Types drop-down menu, select one or more resource types that policies in this policy set will use.

    Tip

    To remove a resource type from the policy set, select the label, and then press Delete or Backspace.

  5. Click Create to save a new policy set or Save Changes to save modifications to an existing policy set.

    Configuring Policy Sets in the AM Console
    Configuring policy sets in the AM console.

To make use of a policy set and any policies it contains, you must configure a policy agent to use the policy set for policy decisions. For details see "To Specify the Realm and Application for Policy Decisions" in the Setup and Maintenance Guide.

Note

Once a policy set is created, users can only change the displayName of an existing policy set, not the ID, without deleting the associated policies.

2.1.1.3. Configuring Policies

This section describes the process of using the AM console to configure policies, which are used to protect a web site, web application, or other resource.

To Configure a Policy Using the AM Console
  1. In the AM console, select Realms > Realm Name > Authorization > Policy Sets, and then click the name of the policy set in which to configure a policy:

  2. To create a new policy, click Add a Policy.

  3. In the Name field, enter a descriptive name for the policy.

    Note

    Do not use special characters within resource type, policy, or policy set names (for example, "my+resource+type") when using the AM console or REST endpoints. Using the special characters listed below causes OpenAM to return a 400 Bad Request error. The special characters are: double quotes ("), plus sign (+), comma (,), less than (<), equals (=), greater than (>), backslash (\), forward slash (/), semicolon (;), and null (\u0000).

  4. To define resources that the policy applies to, follow the steps below:

    1. Select a resource type from the Resource Type drop-down list. The set of resource patterns within the selected resource type will populate the Resources drop-down list. For information on configuring resource types, see "Configuring Resource Types".

    2. Select a resource pattern from the Resources drop-down list.

    3. (Optional) Optionally, replace the asterisks with values to define the resources that the policy applies to.

      Editing Resource Patterns Policies
      Edit the resource pattern if required.

      For information on specifying patterns for matching resources, see "Specifying Resource Patterns with Wildcards".

    4. Click Add to save the resource.

      The AM console displays a page for your new policy. The Tab pages let you modify the policy's properties.

    Tip

    To remove a resource, click the Delete icon.

  5. Repeat these steps to add all the resources to which your policy applies, and then click Create.

  6. To configure the policy's actions, select the Actions tab and perform the following:

    1. Select an action that the policy applies to by selecting them from the Add an Action drop-down list.

    2. Select whether to allow or deny the action on the resources specified earlier.

      Allowing or Denying the Action for the Resource
      Select the actions and whether to allow or deny the action for the resources specified.

    3. Repeat these steps to add all the appropriate actions, and then click Save Changes.

  7. Define conditions in the AM console by combining logical operators with blocks of configured parameters to create a rule set that the policy uses to filter requests for resources. Use drag and drop to nest logical operators at multiple levels to create complex rule sets.

    Valid drop-points in which to drop a block are displayed with a grey horizontal bar.

    Valid Drop Point
    Valid drop points to drop a block in are shown as a grey horizontal band.

    1. To define the subjects that the policy applies to, complete the following steps on the Subjects tab:

      1. Click Add a Subject Condition, choose the type from the drop-down menu, specify any required subject values, click the checkmark to the right when done, and then drag the block into a valid drop point in the rule set above.

        Nesting subject conditions
        Combine logical and subject conditions to create complex policies.

        The available subject condition types are:

        Authenticated Users

        Any user that has successfully authenticated with OpenAM.

        Users & Groups

        A user or group as defined in the Subjects pages of the realm the policy is created in.

        Select one or more users or groups from the User Subjects or Group Subjects drop-down lists, which display the subjects and groups available within the realm.

        To remove an entry, click the value, and then press Delete (Windows/GNU/Linux) or Backspace (Mac OS X).

        OpenID Connect/Jwt Claim

        Validate a claim within a JSON Web Token (JWT).

        Type the name of the claim to validate in the Claim Name field, for example sub, and the required value in the Claim Value field, and then click the checkmark.

        Repeat the step to enter additional claims.

        The claim(s) will be part of the JWT payload together with the JWT header and signature. The JWT is sent in the authorization header of the bearer token.

        This condition type only supports string equality comparisons, and is case-sensitive.

        Never Match

        Never match any subject. Has the effect of disabling the policy, as it will never match a subject.

        If you do not set a subject condition, "Never Match" is the default. In other words, you must set a subject condition for the policy to apply.

        To match regardless of the subject, configure a subject condition that is "Never Match" inside a logical Not block.

      2. To add a logical operator, click the Add a Logical Operator button, choose between All Of, Not, and Any Of from the drop-down menu, and then drag the block into a valid drop point in the rule set above.

      3. Continue combining logical operators and subject conditions. To edit an item, click the Edit button. To remove an item, click the Delete button. When complete, click Save Changes.

    2. To configure environment conditions in the policy, complete the following steps on the Environments tab:

      1. To add an environment condition, click the Environment Condition button, choose the type from the drop-down menu, specify any required parameters, and then drag the block into a drop-point in a logical block above.

        The available environment condition types are:

        Active Session Time

        Make the policy test how long the user's stateful or stateless session has been active, as specified in Max Session Time. To terminate the session if it has been active for longer than the specified time, set Terminate Sessions to True. The user will need to re-authenticate.

        Authentication by Module Chain

        Make the policy test the service that was used to authenticate the user.

        Authentication by Module Instance

        Make the policy test the authentication module used to authenticate, specified in Authentication Scheme. Specify a timeout for application authentication in Application Idle Timeout Scheme and the name of the application in Application Name.

        Authentication Level (greater than or equal to)

        Make the policy test the minimum acceptable authentication level specified in Authentication Level.

        Authentication to a Realm

        Make the policy test the realm to which the user authenticated.

        Current Session Properties

        Make the policy test property values set in the user's stateful or stateless session.

        Set Ignore Value Case to True to make the test case-insensitive.

        Specify one or more pairs of session properties and values using the format property:value. For example, specify clientType:genericHTML to test whether the value of the clientType property is equal togenericHTML.

        Identity Membership

        Make the policy apply if the UUID of the invocator is a member of at least one of the AMIdentity objects specified in AM Identity Name.

        Often used to filter requests on the identity of a Web Service Client (WSC).

        IPv4 Address/DNS Name

        Make the policy test the IP version 4 address that the request originated from.

        The IP address is taken from the requestIp value of policy decision requests. If this is not provided, the IP address stored in the SSO token is used instead.

        Specify a range of addresses to test against by entering four sets of up to three digits, separated by full stops (.) in both Start IP and End IP.

        If only one of these values is provided, it is used as a single IP address to match.

        Optionally, specify a DNS name in DNS Name to filter requests to that domain.

        IPv6 Address/DNS Name

        Make the policy test the IP version 6 address that the request originated from.

        The IP address is taken from the requestIp value of policy decision requests. If this is not provided, the IP address stored in the SSO token is used instead.

        Specify a range of addresses to test against by entering eight sets of four hexadecimal characters, separated by a colon (:) in both Start IP and End IP.

        If only one of these values is provided, it is used as a single IP address to match.

        Optionally, specify a DNS name in DNS Name to filter requests to those coming from the specified domain.

        Use an asterisk (*) in the DNS name to match multiple subdomains. For example *.example.com applies to requests coming from www.example.com, secure.example.com, or any other subdomain of example.com.

        LDAP Filter Condition

        Make the policy test whether the user's entry can be found using the LDAP search filter you specify in the directory configured for the policy service, which by default is the identity repository. Navigate to Configure > Global Services, and then click Policy Configuration to see the global LDAP configuration.

        Alternatively, to configure these settings for a realm, navigate to Realms > Realm Name > Services, and then click Policy Configuration.

        OAuth2 Scope

        Make the policy test whether an authorization request includes all of the specified OAuth 2.0 scopes.

        Scope names must follow OAuth 2.0 scope syntax described in RFC 6749, Access Token Scope . As described in that section, separate multiple scope strings with spaces, such as openid profile.

        The scope strings match regardless of order in which they occur, so openid profile is equivalent to profile openid.

        The condition is also met when additional scope strings are provided beyond those required to match the specified list. For example, if the condition specifies openid profile, then openid profile email also matches.

        Resource/Environment/IP Address

        Make the policy apply to a complex condition such as whether the user is making a request from the localhost and has also authenticated with the LDAP authentication module.

        Entries must take the form of an IF...ELSE statement. The IF statement can specify either IP to match the user's IP address, or dnsName to match their DNS name.

        If the IF statement is true, the THEN statement must also be true for the condition to be fulfilled. If not, relevant advice is returned in the policy evaluation request.

        The available parameters for the THEN statement are as follows:

        module

        The module that was used to authenticate the user, for example DataStore.

        service

        The service that was used to authenticate the user.

        authlevel

        The minimum required authentication level.

        role

        The role of the authenticated user.

        user

        The name of the authenticated user.

        redirectURL

        The URL the user was redirected from.

        realm

        The realm that was used to authenticate the user.

        The IP address can be IPv4, IPv6, or a hybrid of the two.

        Example: IF IP=[127.0.0.1] THEN role=admins.

        Time (day, date, time, and timezone)

        Make the policy test when the policy is evaluated.

        The values for day, date and time must be set in pairs that comprise a start and an end.

        Create conditions that apply between a start and end date and time.
        Create conditions that apply between a start and end date and time.

      2. To add a logical operator, click the Logical button, choose between All Of, Not, and Any Of from the drop-down menu, and then drag the block into a valid drop point in the rule set above.

      3. Continue combining logical operators and environment conditions, and when finished, click Save Changes.

  8. (Optional) Add response attributes, retrieved from the user entry in the identity repository, into the headers of the request at policy decision time. The policy agent for the protected resources/applications or the protected resources/applications themselves retrieve the policy response attributes to customize or personalize the application. Policy response attributes come in two formats: subject attributes and static attributes.

    To configure response attributes in the policy, complete the following steps on the Response attributes tab:

    1. To add subject attributes, select them from the Subject attributes drop-down list

      To remove an entry, click the value, and then press Delete (Windows/GNU/Linux) or Backspace (Mac OS X)

    2. To add a static attribute, specify the key-value pair for each static attribute. Enter the Property Name and its corresponding Property Value in the fields, and then click the Add (+) icon.

      Note

      To edit an entry, click the Edit icon in the row containing the attribute, or click the row itself. To remove an entry, click the Delete icon in the row containing the attribute.

    3. Continue adding subject and static attributes, and when finished, click Save Changes.

2.1.1.4. Specifying Resource Patterns with Wildcards

Resource patterns can specify an individual URL or resource name to protect. Alternatively, a resource pattern can match URLs or resource names by using wildcards.

  • The wildcards you can use are * and -*-.

    These wildcards can be used throughout resource patterns to match URLs or resource names. For a resource pattern used to match URLs, wildcards can be employed to match the scheme, host, port, path, and query string of a resource.

    • When used within the path segment of a resource, the wildcard * matches multiple path segments.

      For example, http://www.example.com/* matches http://www.example.com/, http://www.example.com/index.html, and also http://www.example.com/company/images/logo.png.

    • When used within the path segment of a resource, the wildcard -*- will only match a single path segment.

      For example, http://www.example.com/-*- matches http://www.example.com/index.html but does not match http://www.example.com/company/resource.html or http://www.example.com/company/images/logo.png.

  • Wildcards do not match ?. You must explicitly add patterns to match URLs with query strings.

    • When matching URLs sent from a web policy or J2EE agent, an asterisk (*) used at the end of a pattern after a ? character matches one or more characters, not zero or more characters.

      For example, http://www.example.com/*?* matches http://www.example.com/users?_action=create, but not http://www.example.com/users?.

      To match everything under http://www.example.com/ specify three patterns, one for http://www.example.com/*, one for http://www.example.com/*?, and one for http://www.example.com/*?*.

    • When matching resources by using the policies?_action=evaluate REST endpoint, an asterisk (*) used at the end of a pattern after a ? character matches zero or more characters.

      For example, http://www.example.com/*?* matches http://www.example.com/users?_action=create, as well as http://www.example.com/users?.

      To match everything under http://www.example.com/ specify two patterns, one for http://www.example.com/*, one for http://www.example.com/*?*.

  • When defining patterns to match URLs with query strings, OpenAM sorts the query string field-value pairs alphabetically by field name when normalizing URLs before checking whether a policy matches. Therefore the query string ?subject=SPBnfm+t5PlP+ISyQhVlplE22A8=&action=get is equivalent to the query string ?action=get&subject=SPBnfm+t5PlP+ISyQhVlplE22A8=.

  • Duplicate slashes (/) are not considered part of the resource name to match. A trailing slash is considered by OpenAM as part of the resource name.

    For example, http://www.example.com//path/, and http://www.example.com/path// are treated in the same way.

    http://www.example.com/path, and http://www.example.com/path/ are considered two distinct resources.

  • Wildcards can be used to match protocols, host names, and port numbers.

    For example, *://*:*/* matches http://www.example.com:80/index.html, https://www.example.com:443/index.html, and http://www.example.net:8080/index.html.

    When a port number is not explicitly specified, then the default port number is implied. Therefore http://www.example.com/* is the same as http://www.example.com:80/*, and https://www.example.com/* is the same as https://www.example.com:443/*.

  • Wildcards cannot be escaped.

  • Do not mix * and -*- in the same pattern.

  • By default, comparisons are not case sensitive. The delimiter, wildcards and case sensitivity are configurable. To see examples of other configurations, in the AM console, navigate to Configure > Global Services, click Policy Configuration, and scroll to Resource Comparator.

2.1.2. Importing and Exporting Policies

You can import and export policies to and from files.

You can use these files to backup policies, transfer policies between OpenAM instances, or store policy configuration in a version control system such as Git or Subversion.

OpenAM supports exporting policies in JSON and eXtensible Access Control Markup Language (XACML) Version 3.0 format. The features supported by each format are summarized in the table below:

Comparison of Policy Import/Export Formats
FeatureSupported?
JSONXACML
Can be imported/exported from within the AM console?NoYes
Can be imported/exported on the command line, using the ssoadm command?YesYes
Exports policies?YesYes
Exports policy sets?YesPartial [a]
Exports resource types?YesPartial [a]
Creates an exact copy of the original policy sets, resource types, and policies upon import?YesPartial [b]

[a] Only the details of policy sets and resource types that are actually used within a policy is exported to the XACML format. The full definition is not exported.

[b] Policy sets and resource types will be generated from the details in the XML, but may not match the definitions of the originals, for example the names are auto-generated.


Note

OpenAM can only import XACML 3.0 files that were either created by an OpenAM instance, or that have had minor manual modifications, due to the reuse of some XACML 3.0 parameters for non-standard information.

You can import and export policies by using the policy editor in the AM console, using the REST API, or with the ssoadm command.

For information on importing and exporting policies in XACML format by using the REST API, see "Importing and Exporting XACML 3.0".

To Export Policies in XACML Format (AM Console)
  • In the AM console, select Realms > Realm Name > Authorization > Policy Sets, and then click Export Policy Sets.

    All policy sets, and the policies within will be exported in XACML format.

To Import Policies in XACML Format (AM Console)
  1. In the AM console, select Realms > Realm Name > Authorization > Policy Sets, and then click Import Policy Sets.

  2. Browse to the XACML format file, select it, and then click Open.

    Any policy sets, and the policies within will be imported from the selected XACML format file.

    Note

    Policy sets and resource types will be generated from the details in the XACML format file, but may not match the definitions of the originals, for example the names are auto-generated.

To Export Policies in JSON Format (Command Line)
  • Use the ssoadm policy-export command:

    $ ssoadm \
      policy-export \
      --realm "/" \
      --servername "http://openam.example.com:8080/openam" \
      --jsonfile "myPolicies.json" \
      --adminid amadmin \
      --password-file /tmp/pwd.txt
    
    {
      "RESOURCE_TYPE" : 1,
      "POLICY" : 1,
      "APPLICATION" : 1
    }

    If exporting from a subrealm, include the top level realm ("/") in the --realm value. For example --realm "/myRealm".

    For more information on the syntax of this command, see "ssoadm policy-export" in the Reference.

To Import Policies in JSON Format (Command Line)
  • Use the ssoadm policy-import command:

    $ ssoadm \
      policy-import \
      --realm "/myRealm" \
      --servername "http://openam.example.com:8080/openam" \
      --jsonfile "myPolicies.json" \
      --adminid amadmin \
      --password-file /tmp/pwd.txt
    
    {
      "POLICY" : {
        "CREATE_SUCCESS" : {
          "count" : 1
        }
      },
      "RESOURCE_TYPE" : {
        "CREATE_SUCCESS" : {
          "count" : 1
        }
      },
      "APPLICATION" : {
        "CREATE_SUCCESS" : {
          "count" : 1
        }
      }
    }

    If importing to a subrealm, include the top level realm ("/") in the --realm value. For example --realm "/myRealm".

    For more information on the syntax of this command, see "ssoadm policy-import" in the Reference.

To Export Policies in XACML Format (Command Line)
  • Use the ssoadm list-xacml command:

    $ ssoadm \
      list-xacml \
      --realm "/" \
      --adminid amadmin \
      --password-file /tmp/pwd.txt
    
     <?xml version="1.0" encoding="UTF-8"?>
     <PolicySet
     xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
     PolicyCombiningAlgId="urn...rule-combining-algorithm:deny-overrides"
     Version="2014.11.25.17.41.15.597"
     PolicySetId="/:2014.11.25.17.41.15.597">
      <Target />
      <Policy
      RuleCombiningAlgId="urn...rule-combining-algorithm:deny-overrides"
      Version="2014.11.25.17.40.08.067"
      PolicyId="myPolicy">
      <Description />
      <Target>
       <AnyOf>
        <AllOf>
         <Match
          MatchId="urn...entitlement:json-subject-match">
          <AttributeValue
           DataType="urn...entitlement.conditions.subject.AuthenticatedUsers">
           {}
          </AttributeValue>
          <AttributeDesignator
           MustBePresent="true"
           DataType="urn...entitlement.conditions.subject.AuthenticatedUsers"
           AttributeId="urn...entitlement:json-subject"
           Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" />
         </Match>
        </AllOf>
       </AnyOf>
       <AnyOf>
        <AllOf>
         <Match
          MatchId="urn...entitlement:resource-match:application:iPlanetAMWebAgentService">
          <AttributeValue
           DataType="htp://www.w3.org/2001/XMLSchema#string">
           http://www.example.com:8000/*?*
          </AttributeValue>
          <AttributeDesignator
           MustBePresent="true"
           DataType="htp://www.w3.org/2001/XMLSchema#string"
           AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"
           Category="urn...attribute-category:resource" />
         </Match>
        </AllOf>
       </AnyOf>
       <AnyOf>
        <AllOf>
         <Match
          MatchId="urn...application-match">
          <AttributeValue
           DataType="htp://www.w3.org/2001/XMLSchema#string">
           iPlanetAMWebAgentService
          </AttributeValue>
          <AttributeDesignator
           MustBePresent="false"
           DataType="htp://www.w3.org/2001/XMLSchema#string"
           AttributeId="urn...application-id"
           Category="urn...application-category" />
         </Match>
        </AllOf>
       </AnyOf>
       <AnyOf>
        <AllOf>
         <Match
          MatchId="urn...entitlement:action-match:application:iPlanetAMWebAgentService">
          <AttributeValue
           DataType="htp://www.w3.org/2001/XMLSchema#string">
           POST
          </AttributeValue>
          <AttributeDesignator
           MustBePresent="true"
           DataType="htp://www.w3.org/2001/XMLSchema#string"
           AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"
           Category="urn...attribute-category:action" />
         </Match>
        </AllOf>
        <AllOf>
         <Match
          MatchId="urn...entitlement:action-match:application:iPlanetAMWebAgentService">
          <AttributeValue
           DataType="htp://www.w3.org/2001/XMLSchema#string">
           GET
          </AttributeValue>
          <AttributeDesignator
           MustBePresent="true"
           DataType="htp://www.w3.org/2001/XMLSchema#string"
           AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"
           Category="urn...attribute-category:action" />
         </Match>
        </AllOf>
       </AnyOf>
      </Target>
      <VariableDefinition
       VariableId="....entitlement.applicationName">
       <AttributeValue
        DataType="htp://www.w3.org/2001/XMLSchema#string">
        iPlanetAMWebAgentService
       </AttributeValue>
      </VariableDefinition>
      <VariableDefinition
       VariableId="...privilege.createdBy">
       <AttributeValue
        DataType="htp://www.w3.org/2001/XMLSchema#string">
        id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org
       </AttributeValue>
      </VariableDefinition>
      <VariableDefinition
       VariableId="...privilege.lastModifiedBy">
       <AttributeValue
        DataType="htp://www.w3.org/2001/XMLSchema#string">
        id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org
       </AttributeValue>
      </VariableDefinition>
      <VariableDefinition
       VariableId="...privilege.creationDate">
       <AttributeValue
        DataType="htp://www.w3.org/2001/XMLSchema#dateTime">
        2014-11-25T17:40:08.067
       </AttributeValue>
      </VariableDefinition>
      <VariableDefinition
       VariableId="...privilege.lastModifiedDate">
       <AttributeValue
        DataType="htp://www.w3.org/2001/XMLSchema#dateTime">
        2014-11-25T17:40:08.067
       </AttributeValue>
      </VariableDefinition>
      <Rule
       Effect="Permit"
       RuleId="null:permit-rule">
       <Description>Permit Rule</Description>
       <Target>
        <AnyOf>
         <AllOf>
          <Match
           MatchId="urn...entitlement:action-match:application:iPlanetAMWebAgentService">
           <AttributeValue
            DataType="htp://www.w3.org/2001/XMLSchema#string">
            POST
           </AttributeValue>
           <AttributeDesignator
            MustBePresent="true"
            DataType="htp://www.w3.org/2001/XMLSchema#string"
            AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"
            Category="urn...attribute-category:action" />
          </Match>
         </AllOf>
         <AllOf>
          <Match
           MatchId="urn...entitlement:action-match:application:iPlanetAMWebAgentService">
           <AttributeValue
            DataType="htp://www.w3.org/2001/XMLSchema#string">
            GET
           </AttributeValue>
           <AttributeDesignator
            MustBePresent="true"
            DataType="htp://www.w3.org/2001/XMLSchema#string"
            AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"
            Category="urn...attribute-category:action" />
          </Match>
         </AllOf>
        </AnyOf>
       </Target>
       <Condition>
        <Apply
         FunctionId="urn...entitlement:json-subject-and-condition-satisfied">
         <AttributeValue
          DataType="urn...entitlement.conditions.subject.AuthenticatedUsers"
          privilegeComponent="entitlementSubject">
          {}
         </AttributeValue>
        </Apply>
       </Condition>
      </Rule>
     </Policy>
    </PolicySet>
    
     Policy definitions were returned under realm, /.

    For more information on the syntax of this command, see "ssoadm list-xacml" in the Reference.

To Import Policies in XACML Format (Command Line)
  • Use the ssoadm create-xacml command:

    $ ssoadm \
      create-xacml \
      --realm "/" \
      --adminid amadmin \
      --password-file /tmp/pwd.txt \
      --xmlfile policy.xml
    
     Policies were created under realm, /.

    For more information on the syntax of this command, see "ssoadm create-xacml" in the Reference.

2.1.3. Delegating Policy Management

To delegate policy management and other administrative tasks, use privileges. You set privileges in the AM console on the Privileges page for a realm.

For more information, see "Delegating Realm Administration Privileges" in the Setup and Maintenance Guide.

2.2. Implementing Authorization Using the REST API

This section describes how to manage and evaluate policies using OpenAM's REST API.

For general information about the REST API, see "About the REST API".

2.2.1. About the REST Policy Endpoints

OpenAM provides REST APIs both for requesting policy decisions, and also for administering policy definitions.

When making a REST API call, specify the realm in the path component of the endpoint. You must specify the entire hierarchy of the realm, starting at the top-level realm. Prefix each realm in the hierarchy with the realms/ keyword. For example /realms/root/realms/customers/realms/europe.

  • Under /json/realms/root/resourcetypes, you find a JSON-based API for managing resource types.

  • Under /json/realms/root/applications and /json/applicationtypes you find JSON-based APIs for administering policy sets and reading application types.

  • Under /json/realms/root/policies, you find a JSON-based API for policy management and evaluation.

  • Under /json/conditiontypes you find a JSON-based API for viewing what types of conditions you can use when defining policies.

  • Under /json/subjecttypes you find a JSON-based API for viewing what types of subjects you can use when defining policies.

  • Under /json/subjectattributes you find a JSON-based API for viewing subjects' attributes you can use when defining response attributes in policies.

  • Under /json/decisioncombiners you find a JSON-based API for viewing implementations you can use when defining policies to specify how to combine results when multiple policies apply.

Before making a REST API call to request a policy decision or manage a policy component, make sure that you have:

  • Authenticated successfully to OpenAM as a user with sufficient privileges to make the REST API call

  • Obtained the session token returned after successful authentication

When making the REST API call, pass the session token in the HTTP header. For more information about the OpenAM session token and its use in REST API calls, see "Using the Session Token After Authentication".

2.2.2. Requesting Policy Decisions

You can request policy decisions from OpenAM by using the REST APIs described in this section. OpenAM evaluates requests based on the context and the policies configured, and returns decisions that indicate what actions are allowed or denied, as well as any attributes or advice for the resources specified.

To request decisions for specific resources, see "Requesting Policy Decisions For Specific Resources".

To request decisions for a resource and all resources beneath it, see "Requesting Policy Decisions For a Tree of Resources".

2.2.2.1. Requesting Policy Decisions For Specific Resources

This section shows how you can request a policy decision over REST for specific resources.

When making a REST API call, specify the realm in the path component of the endpoint. You must specify the entire hierarchy of the realm, starting at the top-level realm. Prefix each realm in the hierarchy with the realms/ keyword. For example /realms/root/realms/customers/realms/europe.

To request policy decisions for specific resources, perform an HTTP POST using the evaluation action to the appropriate path under the URI where OpenAM is deployed, /json{/realms/root}/policies?_action=evaluate. The payload for the HTTP POST is a JSON object that specifies at least the resources, and takes the following form.

{
    "resources": [
        "resource1",
        "resource2",
        ...,
        "resourceN"
    ],
    "application": "defaults to iPlanetAMWebAgentService if not specified",
    "subject": {
        "ssoToken": "SSO token ID string",
        "jwt": "JSON Web Token string",
        "claims": {
            "key": "value",
            ...
        }
    },
    "environment": {
        "optional key1": [
            "value",
            "another value",
            ...
        ],
        "optional key2": [
            "value",
            "another value",
            ...
        ],
        ...
    }
}

The values for the fields shown above are explained below:

"resources"

This required field specifies the list of resources for which to return decisions.

For example, when using the default policy set, "iPlanetAMWebAgentService", you can request decisions for resource URLs.

{
    "resources": [
        "http://www.example.com/index.html",
        "http://www.example.com/do?action=run"
    ]
}
"application"

This field holds the name of the policy set, and defaults to "iPlanetAMWebAgentService" if not specified.

For more on policy sets, see "Managing Policy Sets".

"subject"

This optional field holds an object that represents the subject. You can specify one or more of the following keys. If you specify multiple keys, the subject can have multiple associated principals, and you can use subject conditions corresponding to any type in the request.

"ssoToken"

The value is the SSO token ID string for the subject, returned for example on successful authentication as described in "Authentication and Logout".

"jwt"

The value is a JWT string.

"claims"

The value is an object (map) of JWT claims to their values.

If you do not specify the subject, OpenAM uses the SSO token ID of the subject making the request.

"environment"

This optional field holds a map of keys to lists of values.

If you do not specify the environment, the default is an empty map.

The example below requests policy decisions for two URL resources. The iPlanetDirectoryPro header sets the SSO token for a user who has access to perform the operation.

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "iPlanetDirectoryPro: AQIC5..." \
 --data '{
    "resources": [
        "http://www.example.com/index.html",
        "http://www.example.com/do?action=run"
    ],
    "application": "iPlanetAMWebAgentService"
 }' \
 https://openam.example.com:8443/openam/json/realms/root/policies?_action=evaluate
 [ {
  "resource" : "http://www.example.com/do?action=run",
  "actions" : {
  },
  "attributes" : {
  },
  "advices" : {
    "AuthLevelConditionAdvice" : [ "3" ]
  }
}, {
  "resource" : "http://www.example.com/index.html",
  "actions" : {
    "POST" : false,
    "GET" : true
  },
  "attributes" : {
    "cn" : [ "demo" ]
  },
  "advices" : {
  }
 }
]

In the JSON list of decisions returned for each resource, OpenAM includes these fields.

"resource"

A resource specified in the request.

The decisions returned are not guaranteed to be in the same order as the resources were requested.

"actions"

A map of action name keys to Boolean values that indicate whether the action is allowed (true) or denied (false) for the specified resource.

In the example, for resource http://www.example.com:80/index.html HTTP GET is allowed, whereas HTTP POST is denied.

"attributes"

A map of attribute names to their values, if any response attributes are returned according to applicable policies.

In the example, the policy that applies to http://www.example.com:80/index.html causes that the value of the subject's "cn" profile attribute to be returned.

"advices"

A map of advice names to their values, if any advice is returned according to applicable policies.

The "advices" field can provide hints regarding what OpenAM needs to take the authorization decision.

In the example, the policy that applies to http://www.example.com:80/do?action=run requests that the subject be authenticated at an authentication level of at least 3.

{
    "advices": {
        "AuthLevelConditionAdvice": [
            "3"
        ]
    }
}

See "Policy Decision Advice" for details.

You can use the query string parameters _prettyPrint=true to make the output easier to read, and _fields=field-name[,field-name...] to limit the fields returned in the output.

2.2.2.2. Policy Decision Advice

When OpenAM returns a policy decision, the JSON for the decision can include an "advices" field. This field contains hints for the policy enforcement point.

{
    "advices": {
        "type": [
            "advice"
        ]
    }
}

The "advices" returned depend on policy conditions. For more information about OpenAM policy conditions, see "Managing Policies".

This section shows examples of the different types of policy decision advice and the conditions that cause OpenAM to return the advice.

"AuthLevel" and "LEAuthLevel" condition failures can result in advice showing the expected or maximum possible authentication level. For example, failure against the following condition:

{
    "type": "AuthLevel",
    "authLevel": 2
}

Leads to this advice:

{
    "AuthLevelConditionAdvice": [
        "2"
    ]
}

An "AuthScheme" condition failure can result in advice showing one or more required authentication modules. For example, failure against the following condition:

{
    "type": "AuthScheme",
    "authScheme": [
        "HOTP"
    ],
    "applicationName": "iPlanetAMWebAgentService",
    "applicationIdleTimeout": 10
}

Leads to this advice:

{
    "AuthSchemeConditionAdvice": [
        "HOTP"
    ]
}

An "AuthenticateToRealm" condition failure can result in advice showing the name of the realm to which authentication is required. For example, failure against the following condition:

{
    "type": "AuthenticateToRealm",
    "authenticateToRealm": "MyRealm"
}

Leads to this advice:

{
    "AuthenticateToRealmConditionAdvice": [
        "/myRealm"
    ]
}

An "AuthenticateToService" condition failure can result in advice showing the name of the required authentication chain. For example, failure against the following condition:

{
    "type": "AuthenticateToService",
    "authenticateToService": "MyAuthnChain"
}

Leads to this advice:

{
    "AuthenticateToServiceConditionAdvice": [
        "MyAuthnChain"
    ]
}

A "ResourceEnvIP" condition failure can result in advice showing that indicates corrective action to be taken to resolve the problem. The advice varies, depending on what the condition tests. For example, failure against the following condition:

{
    "type": "ResourceEnvIP",
    "resourceEnvIPConditionValue": [
        "IF IP=[127.0.0.12] THEN authlevel=4"
    ]
}

Leads to this advice:

{
    "AuthLevelConditionAdvice": [
        "4"
    ]
}

Failure against a different type of "ResourceEnvIP" condition such as the following:

{
    "type": "ResourceEnvIP",
    "resourceEnvIPConditionValue": [
        "IF IP=[127.0.0.11] THEN service=MyAuthnChain"
    ]
}

Leads to this advice:

{
    "AuthenticateToServiceConditionAdvice": [
        "MyAuthnChain"
    ]
}

A "Session" condition failure can result in advice showing that access has been denied because the user's stateful or stateless session has been active longer than allowed by the condition. The advice will also show if the user's session was terminated and reauthentication is required. For example, failure against the following condition:

{
    "type": "Session",
    "maxSessionTime": "10",
    "terminateSession": false
}

Leads to this advice:

{
    "SessionConditionAdvice": [
        "deny"
    ]
}

When policy evaluation denials occur against the following conditions, OpenAM does not return any advice:

  • IPv4

  • IPv6

  • LDAPFilter

  • OAuth2Scope

  • SessionProperty

  • SimpleTime

2.2.2.3. Requesting Policy Decisions For a Tree of Resources

This section shows how you can request policy decisions over REST for a resource and all other resources in the subtree beneath it.

When making a REST API call, specify the realm in the path component of the endpoint. You must specify the entire hierarchy of the realm, starting at the top-level realm. Prefix each realm in the hierarchy with the realms/ keyword. For example /realms/root/realms/customers/realms/europe.

To request policy decisions for a tree of resources, perform an HTTP POST using the evaluation action to the appropriate path under the URI where OpenAM is deployed, for example /json/realms/root/realms/myRealm/policies?_action=evaluateTree The payload for the HTTP POST is a JSON object that specifies at least the root resource, and takes the following form.

{
    "resource": "resource string",
    "application": "defaults to iPlanetAMWebAgentService if not specified",
    "subject": {
        "ssoToken": "SSO token ID string",
        "jwt": "JSON Web Token string",
        "claims": {
            "key": "value",
            ...
        }
    },
    "environment": {
        "optional key1": [
            "value",
            "another value",
            ...
        ],
        "optional key2": [
            "value",
            "another value",
            ...
        ],
        ...
    }
}

The values for the fields shown above are explained below:

"resource"

This required field specifies the root resource for the decisions to return.

For example, when using the default policy set, "iPlanetAMWebAgentService", you can request decisions for resource URLs.

{
    "resource": "http://www.example.com/"
}
"application"

This field holds the name of the policy set, and defaults to "iPlanetAMWebAgentService" if not specified.

For more on policy sets, see "Managing Policy Sets".

"subject"

This optional field holds an object that represents the subject. You can specify one or more of the following keys. If you specify multiple keys, the subject can have multiple associated principals, and you can use subject conditions corresponding to any type in the request.

"ssoToken"

The value is the SSO token ID string for the subject, returned for example on successful authentication as described in, "Authentication and Logout".

"jwt"

The value is a JWT string.

"claims"

The value is an object (map) of JWT claims to their values.

If you do not specify the subject, OpenAM uses the SSO token ID of the subject making the request.

"environment"

This optional field holds a map of keys to lists of values.

If you do not specify the environment, the default is an empty map.

The example below requests policy decisions for http://www.example.com/. The iPlanetDirectoryPro header sets the SSO token for a user who has access to perform the operation, and the subject takes the SSO token of the user who wants to access a resource.

 $ curl \
  --request POST \
  --header "Content-Type: application/json" \
  --header "iPlanetDirectoryPro: AQIC5...NDU1*" \
  --data '{
    "resource": "http://www.example.com/",
    "subject": { "ssoToken": "AQIC5...zE4*" }
  }' \
  https://openam.example.com:8443/openam/json/realms/root/policies?_action=evaluateTree
 [ {
  "resource" : "http://www.example.com/",
  "actions" : {
    "GET" : true,
    "OPTIONS" : true,
    "HEAD" : true
  },
  "attributes" : {
  },
  "advices" : {
  }
}, {
  "resource" : "http://www.example.com/*",
  "actions" : {
    "POST" : false,
    "PATCH" : false,
    "GET" : true,
    "DELETE" : true,
    "OPTIONS" : true,
    "HEAD" : true,
    "PUT" : true
  },
  "attributes" : {
    "myStaticAttr" : [ "myStaticValue" ]
  },
  "advices" : {
  }
}, {
  "resource" : "http://www.example.com/*?*",
  "actions" : {
    "POST" : false,
    "PATCH" : false,
    "GET" : false,
    "DELETE" : false,
    "OPTIONS" : true,
    "HEAD" : false,
    "PUT" : false
  },
  "attributes" : {
  },
  "advices" : {
    "AuthLevelConditionAdvice" : [ "3" ]
  }
} ]

Notice that OpenAM returns decisions not only for the specified resource, but also for matching resource names in the tree whose root is the specified resource.

In the JSON list of decisions returned for each resource, OpenAM includes these fields.

"resource"

A resource name whose root is the resource specified in the request.

The decisions returned are not guaranteed to be in the same order as the resources were requested.

"actions"

A map of action name keys to Boolean values that indicate whether the action is allowed (true) or denied (false) for the specified resource.

In the example, for matching resources with a query string only HTTP OPTIONS is allowed according to the policies configured.

"attributes"

A map of attribute names to their values, if any response attributes are returned according to applicable policies.

In the example, the policy that applies to http://www.example.com:80/* causes a static attribute to be returned.

"advices"

A map of advice names to their values, if any advice is returned according to applicable policies.

The "advices" field can provide hints regarding what OpenAM needs to take the authorization decision.

In the example, the policy that applies to resources with a query string requests that the subject be authenticated at an authentication level of at least 3.

Notice that with the "advices" field present, no "advices" appear in the JSON response.

{
    "advices": {
        "AuthLevelConditionAdvice": [ "3" ]
    }
}

You can use the query string parameters _prettyPrint=true to make the output easier to read, and _fields=field-name[,field-name...] to limit the fields returned in the output.

2.2.3. Managing Resource Types

This section describes the process of using the OpenAM REST API for managing resource types, which define a template for the resources that policies apply to, and the actions associated with those resources.

For information on creating resource types by using the OpenAM console, see "Configuring Resource Types".

Resource types are realm specific, hence the URI for the resource types API can contain a realm component, such as /json{/realm}/resourcetypes. If the realm is not specified in the URI, the top level realm is used.

Resource types are represented in JSON and take the following form. Resource types are built from standard JSON objects and values (strings, numbers, objects, sets, arrays, true, false, and null). Each resource type has a unique, system-generated UUID, which must be used when modifying existing resource types. Renaming a resource type will not affect the UUID.

{
    "uuid": "12345a67-8f0b-123c-45de-6fab78cd01e2",
    "name": "URL",
    "description": "The built-in URL Resource Type available to OpenAM Policies.",
    "patterns": [
        "*://*:*/*?*",
        "*://*:*/*"
    ],
    "actions": {
        "POST": true,
        "PATCH": true,
        "GET": true,
        "DELETE": true,
        "OPTIONS": true,
        "HEAD": true,
        "PUT": true
    },
    "createdBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
    "creationDate": 1422892465848,
    "lastModifiedBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
    "lastModifiedDate": 1422892465848
}

The values for the fields shown in the description are explained below:

"uuid"

String matching the unique identifier OpenAM generated for the resource type when created.

"name"

The name provided for the resource type.

"description"

An optional text string to help identify the resource type.

"patterns"

An array of resource patterns specifying individual URLs or resource names to protect.

For more information on patterns in resource types and policies, see "Specifying Resource Patterns with Wildcards"

"actions"

Set of string action names, each set to a boolean indicating whether the action is allowed.

"createdBy"

A string containing the universal identifier DN of the subject that created the resource type.

"creationDate"

An integer containing the creation date and time, in ISO 8601 format.

"lastModifiedBy"

A string containing the universal identifier DN of the subject that most recently updated the resource type.

If the resource type has not been modified since it was created, this will be the same value as createdBy.

"lastModifiedDate"

An string containing the last modified date and time, in ISO 8601 format.

If the resource type has not been modified since it was created, this will be the same value as creationDate.

2.2.3.1. Querying Resource Types

To list all the resource types in a realm, perform an HTTP GET to the /json{/realm}/resourcetypes endpoint, with a _queryFilter parameter set to true.

Note

If the realm is not specified in the URL, OpenAM returns resource types in the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/resourcetypes?_queryFilter=true
{
    "result": [
    {
        "uuid": "12345a67-8f0b-123c-45de-6fab78cd01e3",
        "name": "LIGHTS",
        "description": "",
        "patterns": [
            "light://*/*"
        ],
        "actions": {
            "switch_off": true,
            "switch_on": true
        },
        "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
        "creationDate": 1431013059131,
        "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
        "lastModifiedDate": 1431013069803
    }
    ],
    "resultCount": 1,
    "pagedResultsCookie": null,
    "remainingPagedResults": 0
}

Additional query strings can be specified to alter the returned results. For more information, see "Query".

Supported _queryFilter Fields and Operators
FieldSupported Operators
uuid Equals (eq), Contains (co), Starts with (sw)
name Equals (eq), Contains (co), Starts with (sw)
description Equals (eq), Contains (co), Starts with (sw)
patterns Equals (eq), Contains (co), Starts with (sw)
actions Equals (eq), Contains (co), Starts with (sw)

2.2.3.2. Reading a Specific Resource Type

To read an individual resource types in a realm, perform an HTTP GET to the /json{/realm}/resourcetypes endpoint, and specify the UUID in the URL.

Note

If the realm is not specified in the URL, OpenAM uses the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/resourcetypes/12345a67-8f0b-123c-45de-6fab78cd01e3
{
    "uuid": "12345a67-8f0b-123c-45de-6fab78cd01e3",
    "name": "LIGHTS",
    "description": "",
    "patterns": [
        "light://*/*"
    ],
    "actions": {
        "switch_off": true,
        "switch_on": true
    },
    "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "creationDate": 1431013059131,
    "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "lastModifiedDate": 1431013069803
}

2.2.3.3. Creating a Resource Type

To create a resource type in a realm, perform an HTTP POST to the /json{/realm}/resourcetypes endpoint, with an _action parameter set to create. Include a JSON representation of the resource type in the POST data.

Note

If the realm is not specified in the URL, OpenAM creates the resource type in the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

Do not use special characters within resource type, policy, or policy set names (for example, "my+resource+type") when using the AM console or REST endpoints. Using the special characters listed below causes OpenAM to return a 400 Bad Request error. The special characters are: double quotes ("), plus sign (+), comma (,), less than (<), equals (=), greater than (>), backslash (\), forward slash (/), semicolon (;), and null (\u0000).

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "iPlanetDirectoryPro: AQIC5..." \
 --data '{
    "name": "My Resource Type",
    "actions": {
        "LEFT": true,
        "RIGHT": true,
        "UP": true,
        "DOWN": true
    },
    "patterns": [
        "http://device/location/*"
    ]
 }' \
 https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/resourcetypes/?_action=create
{
    "uuid": "12345a67-8f0b-123c-45de-6fab78cd01e4",
    "name": "My Resource Type",
    "description": null,
    "patterns": [
        "http://device/location/*"
    ],
    "actions": {
        "RIGHT": true,
        "DOWN": true,
        "UP": true,
        "LEFT": true
    },
    "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "creationDate": 1431099940616,
    "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "lastModifiedDate": 1431099940616
}

2.2.3.4. Updating a Resource Type

To update an individual resource type in a realm, perform an HTTP PUT to the /json{/realm}/resourcetypes endpoint, and specify the UUID in both the URL and the PUT body. Include a JSON representation of the updated resource type in the PUT data, alongside the UUID.

Note

If the realm is not specified in the URL, OpenAM uses the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

Do not use special characters within resource type, policy, or policy set names (for example, "my+resource+type") when using the AM console or REST endpoints. Using the special characters listed below causes OpenAM to return a 400 Bad Request error. The special characters are: double quotes ("), plus sign (+), comma (,), less than (<), equals (=), greater than (>), backslash (\), forward slash (/), semicolon (;), and null (\u0000).

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 --request PUT \
 --header "Content-Type: application/json" \
 --data '{
    "uuid": "12345a67-8f0b-123c-45de-6fab78cd01e4",
    "name": "My Updated Resource Type",
    "actions": {
        "LEFT": false,
        "RIGHT": false,
        "UP": false,
        "DOWN": false
    },
    "patterns": [
        "http://device/location/*"
    ]
 }' \
 https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/resourcetypes/12345a67-8f0b-123c-45de-6fab78cd01e4
{
    "uuid": "12345a67-8f0b-123c-45de-6fab78cd01e4",
    "name": "My Updated Resource Type",
    "description": null,
    "patterns": [
        "http://device/location/*"
    ],
    "actions": {
        "RIGHT": false,
        "DOWN": false,
        "UP": false,
        "LEFT": false
    },
    "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "creationDate": 1431099940616,
    "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "lastModifiedDate": 1431101016427
}

2.2.3.5. Deleting a Specific Resource Type

To delete an individual resource types in a realm, perform an HTTP DELETE to the /json{/realm}/resourcetypes endpoint, and specify the UUID in the URL.

Note

If the realm is not specified in the URL, OpenAM uses the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --request DELETE \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/resourcetypes/12345a67-8f0b-123c-45de-6fab78cd01e4
{}

You can only delete resource types that are not being used by a policy set or policy. Trying to delete a resource type that is in use will return an HTTP 409 Conflict status code, with a message such as:

{
    "code": 409,
    "reason": "Conflict",
    "message": "Unable to remove resource type 12345a67-8f0b-123c-45de-6fab78cd01e4 because it is
                referenced in the policy model."
}

Remove the resource type from any associated policy sets or policies to be able to delete it.

2.2.4. Managing Application Types

Application types act as templates for policy sets, and define how to compare resources and index policies. OpenAM provides a default application type that represents web resources called iPlanetAMWebAgentService. OpenAM policy agents use a default policy set that is based on this type, which is also called iPlanetAMWebAgentService.

OpenAM provides the applicationtypes REST endpoint for the following:

Applications types are server-wide, and do not differ by realm. Hence the URI for the application types API does not contain a realm component, but is /json/applicationtypes.

Application type resources are represented in JSON and take the following form. Application type resources are built from standard JSON objects and values (strings, numbers, objects, arrays, true, false, and null).

{
    "name": "iPlanetAMWebAgentService",
    "actions": {
        "POST": true,
        "PATCH": true,
        "GET": true,
        "DELETE": true,
        "OPTIONS": true,
        "PUT": true,
        "HEAD": true
    },
    "resourceComparator": "com.sun.identity.entitlement.URLResourceName",
    "saveIndex": "org.forgerock.openam.entitlement.indextree.TreeSaveIndex",
    "searchIndex": "org.forgerock.openam.entitlement.indextree.TreeSearchIndex",
    "applicationClassName": "com.sun.identity.entitlement.Application"
}

The values for the fields shown in the description are explained below:

"name"

The name provided for the application type.

"actions"

Set of string action names, each set to a boolean indicating whether the action is allowed.

"resourceComparator"

Class name of the resource comparator implementation used in the context of this application type.

The following implementations are available:

"com.sun.identity.entitlement.ExactMatchResourceName"
"com.sun.identity.entitlement.PrefixResourceName"
"com.sun.identity.entitlement.RegExResourceName"
"com.sun.identity.entitlement.URLResourceName"
"saveIndex"

Class name of the implementation for creating indexes for resource names, such as "com.sun.identity.entitlement.util.ResourceNameIndexGenerator" for URL resource names.

"searchIndex"

Class name of the implementation for searching indexes for resource names, such as "com.sun.identity.entitlement.util.ResourceNameSplitter" for URL resource names.

"applicationClassName"

Class name of the application type implementation, such as "com.sun.identity.entitlement.Application".

2.2.4.1. Querying Application Types

To list all application types, perform an HTTP GET to the /json/applicationtypes endpoint, with a _queryFilter parameter set to true.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/applicationtypes?_queryFilter=true
{
    "result" : [ ... application types ... ],
    "resultCount" : 8,
    "pagedResultsCookie" : null,
    "remainingPagedResults" : -1
}

Additional query strings can be specified to alter the returned results. For more information, see "Query".

2.2.4.2. Reading a Specific Application Type

To read an individual application type, perform an HTTP GET to the /json/applicationtypes endpoint, and specify the application type name in the URL.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/applicationtypes/iPlanetAMWebAgentService
{
    "name": "iPlanetAMWebAgentService",
    "actions": {
        "POST": true,
        "PATCH": true,
        "GET": true,
        "DELETE": true,
        "OPTIONS": true,
        "PUT": true,
        "HEAD": true
    },
    "resourceComparator": "com.sun.identity.entitlement.URLResourceName",
    "saveIndex": "org.forgerock.openam.entitlement.indextree.TreeSaveIndex",
    "searchIndex": "org.forgerock.openam.entitlement.indextree.TreeSearchIndex",
    "applicationClassName": "com.sun.identity.entitlement.Application"
}

2.2.5. Managing Policy Sets

This section describes the process of using the OpenAM REST API for managing policy sets.

Policy set definitions set constraints for defining policies. The default built-in policy set is called iPlanetAMWebAgentService, which OpenAM policy agents use to allow policy management through the AM console.

For information on creating policy sets by using the OpenAM console, see "Configuring Policy Sets".

Policy sets are realm specific, hence the URI for the policy set API can contain a realm component, such as /json{/realm}/applications. If the realm is not specified in the URI, the top level realm is used.

Policy sets are represented in JSON and take the following form. Policy sets are built from standard JSON objects and values (strings, numbers, objects, arrays, true, false, and null).

{
    "creationDate": 1431351677264,
    "lastModifiedDate": 1431351677264,
    "conditions": [
        "AuthenticateToService",
        "Script",
        "AuthScheme",
        "IPv6",
        "SimpleTime",
        "OAuth2Scope",
        "IPv4",
        "AuthenticateToRealm",
        "OR",
        "AMIdentityMembership",
        "LDAPFilter",
        "AuthLevel",
        "SessionProperty",
        "LEAuthLevel",
        "Session",
        "NOT",
        "AND",
        "ResourceEnvIP"
    ],
    "applicationType": "iPlanetAMWebAgentService",
    "subjects": [
        "JwtClaim",
        "AuthenticatedUsers",
        "Identity",
        "NOT",
        "AND",
        "NONE",
        "OR"
    ],
    "entitlementCombiner": "DenyOverride",
    "saveIndex": null,
    "searchIndex": null,
    "resourceComparator": null,
    "resourceTypeUuids": [
        "12345a67-8f0b-123c-45de-6fab78cd01e4"
    ],
    "attributeNames": [ ],
    "editable": true,
    "createdBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
    "lastModifiedBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
    "description": "The built-in Application used by OpenAM Policy Agents.",
    "realm": "/",
    "name": "iPlanetAMWebAgentService"
}

The values for the fields shown in the description are explained below:

"conditions"

Condition types allowed in the context of this policy set.

For information on condition types, see "Managing Policies" and "Managing Environment Condition Types".

"applicationType"

Name of the application type used as a template for this policy set.

"subjects"

Subject types allowed in the context of this policy set.

For information on subject types, see "Managing Policies" and "Managing Subject Condition Types".

"entitlementCombiner"

Name of the decision combiner, such as "DenyOverride".

For more on decision combiners, see "Managing Decision Combiners".

"saveIndex"

Class name of the implementation for creating indexes for resource names, such as "com.sun.identity.entitlement.util.ResourceNameIndexGenerator" for URL resource names.

"searchIndex"

Class name of the implementation for searching indexes for resource names, such as "com.sun.identity.entitlement.util.ResourceNameSplitter" for URL resource names.

"resourceComparator"

Class name of the resource comparator implementation used in the context of this policy set.

The following implementations are available:

"com.sun.identity.entitlement.ExactMatchResourceName"
"com.sun.identity.entitlement.PrefixResourceName"
"com.sun.identity.entitlement.RegExResourceName"
"com.sun.identity.entitlement.URLResourceName"
"resourceTypeUuids"

A list of the UUIDs of the resource types associated with the policy set.

"attributeNames"

A list of attribute names such as cn. The list is used to aid policy indexing and lookup.

"description"

String describing the policy set.

"realm"

Name of the realm where this policy set is defined. You must specify the realm in the policy set JSON even though it can be derived from the URL that is used when creating the policy set.

"name"

String matching the name in the URL used when creating the policy set by HTTP PUT or in the body when creating the policy set by HTTP POST.

"createdBy"

A string containing the universal identifier DN of the subject that created the policy set.

"creationDate"

An integer containing the creation date and time, in number of seconds since the Unix epoch (1970-01-01T00:00:00Z).

"lastModifiedBy"

A string containing the universal identifier DN of the subject that most recently updated the policy set.

If the policy set has not been modified since it was created, this will be the same value as createdBy.

"lastModifiedDate"

An integer containing the last modified date and time, in number of seconds since the Unix epoch (1970-01-01T00:00:00Z).

If the policy set has not been modified since it was created, this will be the same value as creationDate.

2.2.5.1. Querying Policy Sets

To list all the policy sets in a realm, perform an HTTP GET to the /json{/realm}/applications endpoint, with a _queryFilter parameter set to true.

Note

If the realm is not specified in the URL, OpenAM returns policy sets in the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/applications?_queryFilter=true
{
 {
 "result": [
 {
   "_id": "iPlanetAMWebAgentService",
   "name": "iPlanetAMWebAgentService",
   "displayName": "Default Policy Set",
   "subjects": [
     "NOT",
     "OR",
     "JwtClaim",
     "AuthenticatedUsers",
     "AND",
     "Identity",
     "NONE"
   ],
   "saveIndex": null,
   "searchIndex": null,
   "entitlementCombiner": "DenyOverride",
   "resourceComparator": null,
   "attributeNames": [
   ],
   "lastModifiedBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
   "editable": true,
   "resourceTypeUuids": [
     "76656a38-5f8e-401b-83aa-4ccb74ce88d2"
   ],
   "creationDate": 1480651214923,
   "lastModifiedDate": 1480651214923,
   "createdBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
   "description": "The built-in Application used by OpenAM Policy Agents.",
   "applicationType": "iPlanetAMWebAgentService",
   "conditions": [
     "LEAuthLevel",
     "Script",
     "AuthenticateToService",
     "SimpleTime",
     "AMIdentityMembership",
     "OR",
     "IPv6",
     "IPv4",
     "SessionProperty",
     "AuthScheme",
     "AuthLevel",
     "NOT",
     "AuthenticateToRealm",
     "AND",
     "ResourceEnvIP",
     "LDAPFilter",
     "OAuth2Scope",
     "Session"
   ]
 },
 {
   "_id": "sunAMDelegationService",
   "name": "sunAMDelegationService",
   "displayName": "Delegation Policy Set",
   "subjects": [
     "NOT",
     "OR",
     "AuthenticatedUsers",
     "AND",
     "Identity"
   ],
   "saveIndex": null,
   "searchIndex": null,
   "entitlementCombiner": "DenyOverride",
   "resourceComparator": null,
   "attributeNames": [

   ],
   "lastModifiedBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
   "editable": true,
   "resourceTypeUuids": [
     "20a13582-1f32-4f83-905f-f71ff4e2e00d"
   ],
   "creationDate": 1480651214933,
   "lastModifiedDate": 1480651214933,
   "createdBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
   "description": null,
   "applicationType": "sunAMDelegationService",
   "conditions": [

   ]
  }
 ],
 "resultCount": 2,
 "pagedResultsCookie": null,
 "totalPagedResultsPolicy": "NONE",
 "totalPagedResults": -1,
 "remainingPagedResults": 0
}

Additional query strings can be specified to alter the returned results. For more information, see "Query".

Supported _queryFilter Fields and Operators
FieldSupported Operators

name

Equals (eq)

description

Equals (eq)

createdBy

Equals (eq)

creationDate

Equals (eq), Greater than or equal to (ge), Greater than (gt), Less than or equal to (le), Less than (lt)

Note

The implementation of eq for this date field does not use regular expression pattern matching.

lastModifiedBy

Equals (eq)

lastModifiedDate

Equals (eq), Greater than or equal to (ge), Greater than (gt), Less than or equal to (le), Less than (lt)

Note

The implementation of eq for this date field does not use regular expression pattern matching.


2.2.5.2. Reading a Specific Policy Set

To read an individual policy set in a realm, perform an HTTP GET to the /json{/realm}/applications endpoint, and specify the policy set name in the URL.

Note

If the realm is not specified in the URL, OpenAM uses the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/applications/mypolicyset
{
    "creationDate": 1431360678810,
    "lastModifiedDate": 1431360678810,
    "conditions": [
        "AuthenticateToService",
        "AuthScheme",
        "IPv6",
        "SimpleTime",
        "OAuth2Scope",
        "IPv4",
        "AuthenticateToRealm",
        "OR",
        "AMIdentityMembership",
        "LDAPFilter",
        "SessionProperty",
        "AuthLevel",
        "LEAuthLevel",
        "Session",
        "NOT",
        "AND",
        "ResourceEnvIP"
    ],
    "applicationType": "iPlanetAMWebAgentService",
    "subjects": [
        "JwtClaim",
        "AuthenticatedUsers",
        "Identity",
        "NOT",
        "AND",
        "OR"
    ],
    "entitlementCombiner": "DenyOverride",
    "saveIndex": null,
    "searchIndex": null,
    "resourceComparator": "com.sun.identity.entitlement.URLResourceName",
    "resourceTypeUuids": [
        "12345a67-8f0b-123c-45de-6fab78cd01e2"
    ],
    "attributeNames": [ ],
    "editable": true,
    "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "description": "My example policy set.",
    "realm": "/",
    "name": "mypolicyset"
 }

You can use the query string parameters _prettyPrint=true to make the output easier to read, and _fields=field-name[,field-name...] to limit the fields returned in the output.

2.2.5.3. Creating Policy Sets

To create a policy set in a realm, perform an HTTP POST to the /json{/realm}/applications endpoint, with an _action parameter set to create. Include a JSON representation of the policy set in the POST data.

Note

If the realm is not specified in the URL, OpenAM creates the policy set in the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

Do not use special characters within resource type, policy, or policy set names (for example, "my+resource+type") when using the AM console or REST endpoints. Using the special characters listed below causes OpenAM to return a 400 Bad Request error. The special characters are: double quotes ("), plus sign (+), comma (,), less than (<), equals (=), greater than (>), backslash (\), forward slash (/), semicolon (;), and null (\u0000).

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "iPlanetDirectoryPro: AQIC5..." \
 --data '{
    "name": "mypolicyset",
    "resourceTypeUuids": [
        "12345a67-8f0b-123c-45de-6fab78cd01e2"
    ],
    "realm": "/",
    "conditions": [
        "AND",
        "OR",
        "NOT",
        "AMIdentityMembership",
        "AuthLevel",
        "AuthScheme",
        "AuthenticateToRealm",
        "AuthenticateToService",
        "IPv4",
        "IPv6",
        "LDAPFilter",
        "LEAuthLevel",
        "OAuth2Scope",
        "ResourceEnvIP",
        "Session",
        "SessionProperty",
        "SimpleTime"
    ],
    "applicationType": "iPlanetAMWebAgentService",
    "description": "My example policy set.",
    "resourceComparator": "com.sun.identity.entitlement.URLResourceName",
    "subjects": [
        "AND",
        "OR",
        "NOT",
        "AuthenticatedUsers",
        "Identity",
        "JwtClaim"
    ],
    "entitlementCombiner": "DenyOverride",
    "saveIndex": null,
    "searchIndex": null,
    "attributeNames": []
 }' \
 https://openam.example.com:8443/openam/json/realms/root/applications/?_action=create
{
    "creationDate": 1431360678810,
    "lastModifiedDate": 1431360678810,
    "conditions": [
        "AuthenticateToService",
        "AuthScheme",
        "IPv6",
        "SimpleTime",
        "OAuth2Scope",
        "IPv4",
        "AuthenticateToRealm",
        "OR",
        "AMIdentityMembership",
        "LDAPFilter",
        "SessionProperty",
        "AuthLevel",
        "LEAuthLevel",
        "Session",
        "NOT",
        "AND",
        "ResourceEnvIP"
    ],
    "applicationType": "iPlanetAMWebAgentService",
    "subjects": [
        "JwtClaim",
        "AuthenticatedUsers",
        "Identity",
        "NOT",
        "AND",
        "OR"
    ],
    "entitlementCombiner": "DenyOverride",
    "saveIndex": null,
    "searchIndex": null,
    "resourceComparator": "com.sun.identity.entitlement.URLResourceName",
    "resourceTypeUuids": [
        "12345a67-8f0b-123c-45de-6fab78cd01e2"
    ],
    "attributeNames": [ ],
    "editable": true,
    "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "description": "My example policy set.",
    "realm": "/",
    "name": "mypolicyset"
}

You can use the query string parameters _prettyPrint=true to make the output easier to read, and _fields=field-name[,field-name...] to limit the fields returned in the output.

2.2.5.4. Updating Policy Sets

To update an individual policy set in a realm, perform an HTTP PUT to the /json{/realm}/applications endpoint, and specify the policy set name in the URL. Include a JSON representation of the updated policy set in the PUT data.

Note

If the realm is not specified in the URL, OpenAM uses the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

Do not use special characters within resource type, policy, or policy set names (for example, "my+resource+type") when using the AM console or REST endpoints. Using the special characters listed below causes OpenAM to return a 400 Bad Request error. The special characters are: double quotes ("), plus sign (+), comma (,), less than (<), equals (=), greater than (>), backslash (\), forward slash (/), semicolon (;), and null (\u0000).

$ curl \
 --request PUT \
 --header "iPlanetDirectoryPro: AQIC5..." \
 --header "Content-Type: application/json" \
 --data '{
    "name": "myupdatedpolicyset",
    "description": "My updated policy set - new name and fewer allowable conditions/subjects.",
    "conditions": [
        "NOT",
        "SimpleTime"
    ],
    "subjects": [
        "AND",
        "OR",
        "NOT",
        "AuthenticatedUsers",
        "Identity"
    ],
    "applicationType": "iPlanetAMWebAgentService",
    "entitlementCombiner": "DenyOverride",
    "resourceTypeUuids": [
        "76656a38-5f8e-401b-83aa-4ccb74ce88d2"
    ]
 }' \
 https://openam.example.com:8443/openam/json/realms/root/applications/mypolicyset
{
    "creationDate": 1431362370739,
    "lastModifiedDate": 1431362390817,
    "conditions": [
        "NOT",
        "SimpleTime"
    ],
    "resourceComparator": "com.sun.identity.entitlement.URLResourceName",
    "resourceTypeUuids": [
        "76656a38-5f8e-401b-83aa-4ccb74ce88d2"
    ],
    "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "applicationType": "iPlanetAMWebAgentService",
    "subjects": [
        "AuthenticatedUsers",
        "Identity",
        "NOT",
        "AND",
        "OR"
    ],
    "entitlementCombiner": "DenyOverride",
    "saveIndex": null,
    "searchIndex": null,
    "attributeNames": [ ],
    "editable": true,
    "description": "My updated policy set - new name and fewer allowable conditions/subjects.",
    "realm": "/",
    "name": "myupdatedpolicyset"
}

You can use the query string parameters _prettyPrint=true to make the output easier to read, and _fields=field-name[,field-name...] to limit the fields returned in the output.

2.2.5.5. Deleting Policy Sets

To delete an individual policy set in a realm, perform an HTTP DELETE to the /json{/realm}/applications endpoint, and specify the policy set name in the URL.

Note

If the realm is not specified in the URL, OpenAM uses the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --request DELETE \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/applications/myupdatedpolicyset
{}

2.2.6. Managing Policies

This section describes the process of using the OpenAM REST API for managing policies.

For information on creating policies by using the OpenAM console, see "Configuring Policies".

Policies are realm specific, hence the URI for the policies API can contain a realm component, such as /json{/realm}/policies. If the realm is not specified in the URI, the top level realm is used.

Policy resources are represented in JSON and take the following form. Policy resources are built from standard JSON objects and values (strings, numbers, objects, arrays, true, false, and null).

{
    "name": "mypolicy",
    "active": true,
    "description": "My Policy.",
    "applicationName": "iPlanetAMWebAgentService",
    "actionValues": {
        "POST": true,
        "GET": true
    },
    "resources": [
        "http://www.example.com:80/*",
        "http://www.example.com:80/*?*"
    ],
    "subject": {
        "type": "AuthenticatedUsers"
    },
    "condition": {
        "type": "SimpleTime",
        "startTime": "09:00",
        "endTime": "17:00",
        "startDay": "mon",
        "endDay": "fri",
        "enforcementTimeZone": "GMT"
    },
    "resourceTypeUuid": "76656a38-5f8e-401b-83aa-4ccb74ce88d2",
    "resourceAttributes": [
        {
            "type": "User",
            "propertyName": "givenName",
            "propertyValues": [ ]
        }
    ],
    "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "lastModifiedDate": "2015-05-11T17:39:09.393Z",
    "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "creationDate": "2015-05-11T17:37:24.556Z"
}

The values for the fields shown in the example are explained below:

"name"

String matching the name in the URL used when creating the policy by HTTP PUT or in the body when creating the policy by HTTP POST.

"active"

Boolean indicating whether OpenAM considers the policy active for evaluation purposes, defaults to false.

"description"

String describing the policy.

"resources"

List of the resource name pattern strings to which the policy applies. Must conform to the pattern templates provided by the associated resource type.

"applicationName"

String containing the policy set name, such as "iPlanetAMWebAgentService", or "mypolicyset".

"actionValues"

Set of string action names, each set to a boolean indicating whether the action is allowed. Chosen from the available actions provided by the associated resource type.

Tip

Action values can also be expressed as numeric values. When using numeric values, use the value 0 for false and use any non-zero numeric value for true.

"subject"

Specifies the subject conditions to which the policy applies, where subjects can be combined by using the built-in types "AND", "OR", and "NOT", and where subject implementations are pluggable.

Subjects are shown as JSON objects with "type" set to the name of the implementation (using a short name for all registered subject implementations), and also other fields depending on the implementation. The subject types registered by default include the following:

  • "AuthenticatedUsers", meaning any user that has successfully authenticated to OpenAM.

    {
        "type": "AuthenticatedUsers"
    }       

    Warning

    The AuthenticatedUsers subject condition does not take into account the realm to which a user authenticated. Any user that has authenticated successfully to any realm passes this subject condition.

    To test whether a user has authenticated successfully to a specific realm, also add the AuthenticateToRealm environment condition.

  • "Identity" to specify one or more users from an OpenAM identity repository:

    {
       "type": "Identity",
       "subjectValues": [
           "uid=scarter,ou=People,dc=example,dc=com",
           "uid=ahall,ou=People,dc=example,dc=com"
       ]
    }

    You can also use the "Identity" subject type to specify one or more groups from an identity repository:

    {
        "type": "Identity",
        "subjectValues": [
            "cn=HR Managers,ou=Groups,dc=example,dc=com"
        ]
    }
  • "JwtClaim" to specify a claim in a user's JSON web token (JWT).

    {
        "type": "JwtClaim",
        "claimName": "sub",
        "claimValue": "scarter"
    }
  • "NONE", meaning never match any subject. The result is not that access is denied, but rather that the policy itself does not match and therefore cannot be evaluated in order to allow access.

The following example defines the subject either as the user Sam Carter from an OpenAM identity repository, or as a user with a JWT claim with a subject claim with the value scarter:

"subject": {
    "type": "OR",
    "subjects": [
       {
           "type": "Identity",
           "subjectValues": [
               "uid=scarter,ou=People,dc=example,dc=com"
           ]
       },
       {
           "type": "JwtClaim",
           "claimName": "sub",
           "claimValue": "scarter"
       }
   ]
}

To read a single subject type description, or to list all the available subject types, see "Managing Subject Condition Types".

"condition"

Specifies environment conditions, where conditions can be combined by using the built-in types "AND", "OR", and "NOT", and where condition implementations are pluggable.

Conditions are shown as JSON objects with "type" set to the name of the implementation (using a short name for all registered condition implementations), and also other fields depending on the implementation. The condition types registered by default include the following.

  • "AMIdentityMembership" to specify a list of OpenAM users and groups.

    {
        "type": "AMIdentityMembership",
        "amIdentityName": [
            "id=scarter,ou=People,dc=example,dc=com"
        ]
    }
  • "AuthLevel" to specify the authentication level.

    {
        "type": "AuthLevel",
        "authLevel": 2
    }
  • "AuthScheme" to specify the authentication module used to authenticate and the policy set name, and to set a timeout for authentication.

    {
        "type": "AuthScheme",
        "authScheme": [
            "DataStore"
        ],
        "applicationName": "iPlanetAMWebAgentService",
        "applicationIdleTimeout": 10
    }
  • "AuthenticateToRealm" to specify the realm to which the user authenticated.

    {
        "type": "AuthenticateToRealm",
        "authenticateToRealm": "MyRealm"
    }
  • "AuthenticateToService" to specify the authentication chain that was used to authenticate.

    {
        "type": "AuthenticateToService",
        "authenticateToService": "MyAuthnChain"
    }
  • "IPv4" or "IPv6" to specify an IP address range from which the request originated.

    {
       "type": "IPv4",
       "startIp": "127.0.0.1",
       "endIp": "127.0.0.255"
    }

    You can also use the "IPv4" and "IPv6" conditions with the "dnsName" field to specify domain names from which the request originated. Omit "startIp" and "endIp" when using "dnsName".

    {
        "type": "IPv4",
        "dnsName": [
            "*.example.com"
        ]
    }
  • "LDAPFilter" to specify an LDAP search filter. The user's entry is tested against the search filter in the directory configured in the Policy Configuration Service.

    {
        "type": "LDAPFilter",
        "ldapFilter": "(&(c=US)(preferredLanguage=en-us))"
    }
  • "LEAuthLevel" to specify a maximum acceptable authentication level.

    {
        "type": "LEAuthLevel",
        "authLevel": 2
    }
           
  • "OAuth2Scope" to specify a list of attributes that must be present in the user profile.

    {
        "type": "OAuth2Scope",
        "requiredScopes": [
            "name",
            "address",
            "email"
        ]
    }
  • "ResourceEnvIP" to specify a complex condition such as whether the user is making a request from a given host and has authenticated with a given authentication level. For example:

    {
        "type": "ResourceEnvIP",
        "resourceEnvIPConditionValue": [
            "IF IP=[127.168.10.*] THEN authlevel=4"
        ]
    }

    Entries must take the form of one or more IF...ELSE statements. If the IF statement is true, the THEN statement must also be true for the condition to be fulfilled. The IF statement can specify either IP to match the user's IP address, or dnsName to match their DNS name. The IP address can be IPv4 or IPv6 format, or a hybrid of the two, and can include wildcard characters.

    The available parameters for the THEN statement are as follows:

    module

    The module that was used to authenticate the user, for example DataStore.

    service

    The authentication chain that was used to authenticate the user.

    authlevel

    The minimum required authentication level.

    role

    The role of the authenticated user.

    user

    The name of the authenticated user.

    redirectURL

    The URL from which the user was redirected.

    realm

    The realm to which the user authenticated.

  • "Session" to specify how long the user's stateful or stateless session has been active, and to terminate the session if deemed too old, such that the user must authenticate again. Note that OpenAM terminates stateless sessions only if session blacklisting is in effect. For more information about session blacklisting, see "Session Termination" in the Authentication and Single Sign-On Guide.

    {
        "type": "Session",
        "maxSessionTime": "10",
        "terminateSession": false
    }
  • "SessionProperty" to specify attributes set in the user's stateful or stateless session.

    {
        "type": "SessionProperty",
        "ignoreValueCase": true,
        "properties": {
            "CharSet": [
                "UTF-8"
            ],
            "clientType": [
                "genericHTML"
            ]
        }
    }
  • "SimpleTime" to specify a time range, where "type" is the only required field.

    {
        "type": "SimpleTime",
        "startTime": "07:00",
        "endTime": "19:00",
        "startDay": "mon",
        "endDay": "fri",
        "startDate": "2015:01:01",
        "endDate": "2015:12:31",
        "enforcementTimeZone": "GMT+0:00"
    }

The following example defines the condition as neither Saturday or Sunday, nor certain client IP addresses.

{
    "type": "NOT",
    "condition": {
        "type": "OR",
        "conditions": [
            {
                "type": "SimpleTime",
                "startDay": "sat",
                "endDay": "sun",
                "enforcementTimeZone": "GMT+8:00"
            },
            {
                "type": "IPv4",
                "startIp": "192.168.0.1",
                "endIp": "192.168.0.255"
            }
        ]
    }
}

To read a single condition type description, or to list all the available condition types, see "Managing Environment Condition Types".

"resourceTypeUuid"

The UUIDs of the resource type associated with the policy.

"resourceAttributes"

List of attributes to return with decisions. These attributes are known as response attributes.

The response attribute provider is pluggable. The default implementation provides for statically defined attributes and for attributes retrieved from user profiles.

Attributes are shown as JSON objects with "type" set to the name of the implementation (by default either "Static" for statically defined attributes or "User" for attributes from the user profile), "propertyName" set to the attribute names. For static attributes, "propertyValues" holds the attribute values. For user attributes, "propertyValues" is not used; the property values are determined at evaluation time.

"createdBy"

A string containing the universal identifier DN of the subject that created the policy.

"creationDate"

An integer containing the creation date and time, in number of seconds since the Unix epoch (1970-01-01T00:00:00Z).

"lastModifiedBy"

A string containing the universal identifier DN of the subject that most recently updated the policy.

If the policy has not been modified since it was created, this will be the same value as createdBy.

"lastModifiedDate"

An integer containing the last modified date and time, in number of seconds since the Unix epoch (1970-01-01T00:00:00Z).

If the policy has not been modified since it was created, this will be the same value as creationDate.

2.2.6.1. Querying Policies

Use REST calls to list all the policies in a realm, or to find policies that explicitly apply to a given user or group, by using the procedures below:

To List All Policies in a Realm
  • To list all the policies in a realm, perform an HTTP GET to the /json{/realm}/policies endpoint, with an _queryFilter parameter set to true.

    Note

    If the realm is not specified in the URL, OpenAM returns policies in the top level realm.

    The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

    $ curl \
     --header "iPlanetDirectoryPro: AQIC5w..." \
     https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/policies?_queryFilter=true
    {
        "result": [
            {
            "name": "example",
            "active": true,
            "description": "Example Policy",
            "applicationName": "iPlanetAMWebAgentService",
            "actionValues": {
                "POST": false,
                "GET": true
            },
            "resources": [
                "http://www.example.com:80/*",
                "http://www.example.com:80/*?*"
            ],
            "subject": {
                "type": "Identity",
                "subjectValues": [
                    "uid=demo,ou=People,dc=example,dc=com"
                ]
            },
            "resourceTypeUuid": "12345a67-8f0b-123c-45de-6fab78cd01e4",
            "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
            "lastModifiedDate": "2015-05-11T14:48:08.711Z",
            "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
            "creationDate": "2015-05-11T14:48:08.711Z"
            }
        ],
        "resultCount": 1,
        "pagedResultsCookie": null,
        "remainingPagedResults": 0
    }

    Additional query strings can be specified to alter the returned results. For more information, see "Query".

    Supported _queryFilter Fields and Operators
    FieldSupported Operators

    name

    Equals (eq)

    description

    Equals (eq)

    applicationName

    Equals (eq)

    createdBy

    Equals (eq)

    creationDate

    Equals (eq), Greater than or equal to (ge), Greater than (gt), Less than or equal to (le), Less than (lt)

    Note

    The implementation of eq for this date field does not use regular expression pattern matching.

    lastModifiedBy

    Equals (eq)

    lastModifiedDate

    Equals (eq), Greater than or equal to (ge), Greater than (gt), Less than or equal to (le), Less than (lt)

    Note

    The implementation of eq for this date field does not use regular expression pattern matching.


To Query Policies in a Realm by User or Group

You can query policies that explicitly reference a given subject by providing the universal ID (UID) of either a user or group. OpenAM returns any policies that explicitly apply to the user or group as part of a subject condition.

Tip

You can obtain the universal ID for a user or group by using REST. See "Reading Identities using the REST API" in the Setup and Maintenance Guide.

The following caveats apply to querying policies by user or group:

  • Group membership is not considered. For example, querying policies for a specific user will not return policies that only use groups in their subject conditions, even if the user is a member of any of those groups.

  • Wildcards are not supported, only exact matches.

  • Only policies with a subject condition type of Identity are queried—environment conditions are not queried. The Identity subject condition type is labelled as Users & Groups in the policy editor in the AM console.

  • Policies with subject conditions that only contain the user or group in a logical NOT operator are not returned.

To query policies by user or group:

  • Perform an HTTP GET to the /json{/realm}/policies endpoint, with an _queryId parameter set to queryByIdentityUid, and a uid parameter containing the universal ID of the user or group:

    $ curl \
     --get \
     --header "iPlanetDirectoryPro: AQIC5w..." \
     --data "_queryId=queryByIdentityUid" \
     --data "uid=id=demo,ou=user,o=myrealm,ou=services,dc=openam,dc=forgerock,dc=org" \
     https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/policies
     {
      "result" : [ {
        "name" : "mySubRealmPolicy",
        "active" : true,
        "description" : "",
        "resources" : [ "*://*:*/*?*", "*://*:*/*" ],
        "applicationName" : "iPlanetAMWebAgentService",
        "actionValues" : {
          "POST" : true,
          "PATCH" : true,
          "GET" : true,
          "DELETE" : true,
          "OPTIONS" : true,
          "PUT" : true,
          "HEAD" : true
        },
        "subject" : {
          "type" : "Identity",
          "subjectValues" :
          [
            "id=demo,ou=user,o=myrealm,ou=services,dc=openam,dc=forgerock,dc=org"
          ]
        },
        "resourceTypeUuid" : "76656a38-5f8e-401b-83aa-4ccb74ce88d2",
        "lastModifiedBy" : "id=amAdmin,ou=user,dc=openam,dc=forgerock,dc=org",
        "lastModifiedDate" : "2016-05-05T08:45:35.716Z",
        "createdBy" : "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
        "creationDate" : "2016-05-03T13:45:38.137Z"
      } ],
      "resultCount" : 1,
      "pagedResultsCookie" : null,
      "totalPagedResultsPolicy" : "NONE",
      "totalPagedResults" : -1,
      "remainingPagedResults" : 0
    }

    Note

    If the realm is not specified in the URL, OpenAM searches the top level realm.

    The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

2.2.6.2. Reading a Specific Policy

To read an individual policy in a realm, perform an HTTP GET to the /json{/realm}/policies endpoint, and specify the policy name in the URL.

Note

If the realm is not specified in the URL, OpenAM uses the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/policies/example
{
    "result": [
        {
        "name": "example",
        "active": true,
        "description": "Example Policy",
        "applicationName": "iPlanetAMWebAgentService",
        "actionValues": {
            "POST": false,
            "GET": true
        },
        "resources": [
            "http://www.example.com:80/*",
            "http://www.example.com:80/*?*"
        ],
        "subject": {
            "type": "Identity",
            "subjectValues": [
                "uid=demo,ou=People,dc=example,dc=com"
            ]
        },
        "resourceTypeUuid": "12345a67-8f0b-123c-45de-6fab78cd01e4",
        "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
        "lastModifiedDate": "2015-05-11T14:48:08.711Z",
        "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
        "creationDate": "2015-05-11T14:48:08.711Z"
        }
    ],
    "resultCount": 1,
    "pagedResultsCookie": null,
    "remainingPagedResults": 0
}

You can use the query string parameters _prettyPrint=true to make the output easier to read, and _fields=field-name[,field-name...] to limit the fields returned in the output.

2.2.6.3. Creating Policies

To create a policy in a realm, perform an HTTP POST to the /json{/realm}/policies endpoint, with an _action parameter set to create. Include a JSON representation of the policy in the POST data.

Note

If the realm is not specified in the URL, OpenAM uses the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

Do not use special characters within resource type, policy, or policy set names (for example, "my+resource+type") when using the AM console or REST endpoints. Using the special characters listed below causes OpenAM to return a 400 Bad Request error. The special characters are: double quotes ("), plus sign (+), comma (,), less than (<), equals (=), greater than (>), backslash (\), forward slash (/), semicolon (;), and null (\u0000).

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "iPlanetDirectoryPro: AQIC5..." \
 --data '{
    "name": "mypolicy",
    "active": true,
    "description": "My Policy.",
    "applicationName": "iPlanetAMWebAgentService",
    "actionValues": {
        "POST": false,
        "GET": true
    },
    "resources": [
        "http://www.example.com:80/*",
        "http://www.example.com:80/*?*"
    ],
    "subject": {
        "type": "Identity",
        "subjectValues": [
            "uid=demo,ou=People,dc=example,dc=com"
        ]
    },
    "resourceTypeUuid": "12345a67-8f0b-123c-45de-6fab78cd01e4"
 }' \
 https://openam.example.com:8443/openam/json/realms/root/policies?_action=create
 {
    "name": "mypolicy",
    "active": true,
    "description": "My Policy.",
    "applicationName": "iPlanetAMWebAgentService",
    "actionValues": {
        "POST": false,
        "GET": true
    },
    "resources": [
        "http://www.example.com:80/*",
        "http://www.example.com:80/*?*"
    ],
    "subject": {
        "type": "Identity",
        "subjectValues": [
            "uid=demo,ou=People,dc=example,dc=com"
        ]
    },
    "resourceTypeUuid": "12345a67-8f0b-123c-45de-6fab78cd01e4",
    "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "lastModifiedDate": "2015-05-11T14:48:08.711Z",
    "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "creationDate": "2015-05-11T14:48:08.711Z"
}

You can use the query string parameters _prettyPrint=true to make the output easier to read, and _fields=field-name[,field-name...] to limit the fields returned in the output.

2.2.6.4. Updating Policies

To update an individual policy in a realm, perform an HTTP PUT to the /json{/realm}/policies endpoint, and specify the policy name in the URL. Include a JSON representation of the updated policy in the PUT data.

Note

If the realm is not specified in the URL, OpenAM uses the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

Do not use special characters within resource type, policy, or policy set names (for example, "my+resource+type") when using the AM console or REST endpoints. Using the special characters listed below causes OpenAM to return a 400 Bad Request error. The special characters are: double quotes ("), plus sign (+), comma (,), less than (<), equals (=), greater than (>), backslash (\), forward slash (/), semicolon (;), and null (\u0000).

$ curl \
 --request PUT \
 --header "iPlanetDirectoryPro: AQIC5w..." \
 --header "Content-Type: application/json" \
 --data '{
    "name": "myupdatedpolicy",
    "active": true,
    "description": "My Updated Policy.",
    "resources": [
        "http://www.example.com:80/*",
        "http://www.example.com:80/*?*"
    ],
    "actionValues": {
        "POST": true,
        "GET": true
    },
    "subject": {
        "type": "Identity",
        "subjectValues": [
            "uid=scarter,ou=People,dc=example,dc=com",
            "uid=bjenson,ou=People,dc=example,dc=com"
        ]
    },
    "resourceTypeUuid": "12345a67-8f0b-123c-45de-6fab78cd01e4"
}' \
 https://openam.example.com:8443/openam/json/realms/root/policies/mypolicy
 {
    "name": "myupdatedpolicy",
    "active": true,
    "description": "My Updated Policy.",
    "applicationName": "iPlanetAMWebAgentService",
    "actionValues": {
        "POST": true,
        "GET": true
    },
    "resources": [
        "http://www.example.com:80/*",
        "http://www.example.com:80/*?*"
    ],
    "subject": {
        "type": "Identity",
        "subjectValues": [
            "uid=bjenson,ou=People,dc=example,dc=com",
            "uid=scarter,ou=People,dc=example,dc=com"
        ]
    },
    "resourceTypeUuid": "12345a67-8f0b-123c-45de-6fab78cd01e4",
    "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "lastModifiedDate": "2015-05-11T17:26:59.116Z",
    "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
    "creationDate": "2015-05-11T17:25:18.632Z"
}

You can use the query string parameters _prettyPrint=true to make the output easier to read, and _fields=field-name[,field-name...] to limit the fields returned in the output.

2.2.6.5. Deleting Policies

To delete an individual policy in a realm, perform an HTTP DELETE to the /json{/realm}/policies endpoint, and specify the policy name in the URL.

Note

If the realm is not specified in the URL, OpenAM uses the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5w..." \
 --request DELETE \
 https://openam.example.com:8443/openam/json/realms/root/policies/myupdatedpolicy
{}

2.2.6.6. Copying and Moving Policies

You can copy or move an individual policy by performing an HTTP POST to the /json{/realm}/policies/policyName endpoint as follows:

  • Specify the _action=copy or _action=move URL parameter.

  • Specify the realm in which the input policy resides in the URL. If the realm is not specified in the URL, OpenAM copies or moves a policy from the top level realm.

  • Specify the policy to be copied or moved in the URL.

  • Specify the SSO token of an administrative user who has access to perform the operation in the iPlanetDirectoryPro header.

Specify JSON input data as follows:

JSON Input Data for Copying or Moving Individual Policies
ObjectPropertyDescription
toname

The name of the output policy.

Required unless you are copying or moving a policy to a different realm and you want the output policy to have the same name as the input policy.

toapplication

The policy set in which to place the output policy.

Required when copying or moving a policy to a different policy set.

torealm

The realm in which to place the output policy. If not specified, OpenAM copies or moves the policy within the realm identified in the URL.

Required when copying or moving a policy to a different realm.

toresourceType

The UUID of the output policy's resource type.

Required when copying or moving a policy to a different realm.


The follow example copies the policy myPolicy to myNewPolicy. The output policy is placed in the myRealm realm, in the same policy set as the input policy:

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "iPlanetDirectoryPro: AQIC5w..." \
 --data '{
      "to": {
          "name": "myNewPolicy"
      }
 }' \
 https://openam.example.com:8443/openam/json/realms/root/realms/myRealm/policies/myPolicy?_action=copy
{
    "name":"myNewPolicy",
    "active":true,
    "description":"",
    "applicationName":"iPlanetAMWebAgentService",
    "actionValues":{},
    "resources":['"*://*:*/*"],
    "subject":{"type":"NONE"},
    "resourceTypeUuid":"d98e59c9-766a-4934-b5de-8a28a9edc158",
    "lastModifiedBy":"id=amadmin,ou=user,dc=example,dc=com",
    "lastModifiedDate":"2015-12-19T15:22:44.861Z",
    "createdBy":"id=amadmin,ou=user,dc=example,dc=com",
    "creationDate":"2015-12-19T15:22:44.861Z"
}

The following example moves a policy named myPolicy in the myRealm realm to myMovedPolicy in the myOtherRealm realm. The output policy is placed in the iPlanetAMWebAgentService policy set, which is the policy set in which the input policy is located.

The realm myOtherRealm must be configured as follows for the example to run successfully:

  • It must have a resource type that has the same resources as the resource type configured for the myPolicy policy.

  • It must have a policy set named iPlanetAMWebAgentService.

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "iPlanetDirectoryPro: AQIC5w..." \
 --data '{
      "to": {
          "name": "myMovedPolicy",
          "realm": "/myOtherRealm",
          "resourceType: "616b3d02-7a8d-4422-b6a7-174f62afd065"
      }
 }' \
 https://openam.example.com:8443/openam/json/realms/root/realms/myRealm/policies/myPolicy?_action=move
{
    "name":"myMovedPolicy",
    "active":true,
    "description":"",
    "actionValues":{},
    "applicationName":"iPlanetAMWebAgentService",
    "resources":["*://*:*/*"],
    "subject":{"type":"NONE"},
    "resourceTypeUuid":"616b3d02-7a8d-4422-b6a7-174f62afd065",
    "lastModifiedBy":"id=amadmin,ou=user,dc=example,dc=com",
    "lastModifiedDate":"2015-12-21T19:32:59.502Z",
    "createdBy":"id=amadmin,ou=user,dc=example,dc=com",
    "creationDate":"2015-12-21T19:32:59.502Z"
 }

You can also copy and move multiple policies—all the policies in a policy set—in a single operation by performing an HTTP POST to the /json{/realm}/policies endpoint as follows:

  • Specify the _action=copy or _action=move URL parameter.

  • Specify the realm in which the input policies reside as part of the URL. If no realm is specified in the URL, OpenAM copies or moves policies within the top level realm.

  • Specify the SSO token of an administrative user who has access to perform the operation in the iPlanetDirectoryPro header.

Specify JSON input data as follows:

JSON Input Data for Copying or Moving Multiple Policies
ObjectPropertyDescription
fromapplication

The policy set in which the input policies are located.

Required.

toapplication

The policy set in which to store output policies.

Required when copying or moving policies to a different policy set.

torealm

The realm in which to store output policies.

Required when copying or moving policies to a different realm.

tonamePostfix

A value appended to output policy names in order to prevent name clashes.

Required.

resourceTypeMappingVaries; see Description

One or more resource types mappings, where the left side of the mapping specifies the UUID of a resource type used by the input policies and the right side of the mapping specifies the UUID of a resource type used by the output policies. The two resource types should have the same resource patterns.

Required when copying or moving policies to a different realm.


The following example copies all the policies in the iPlanetAMWebAgentService policy set in the myRealm realm to the iPlanetAMWebAgentService policy set in the myOtherRealm realm, appending the string -copy to the output policy names.

The realm myOtherRealm must be configured as follows for the example to run successfully:

  • It must have a resource type that maps to the ccb50c1a-206d-4946-9106-4164e8f2b35b resource type. The two resource types should have the same resource patterns.

  • It must have a policy set named iPlanetAMWebAgentService.

The JSON output shows that a single policy is copied. The policy myNewPolicy is copied to realm myOtherRealm. The copied policy receives the name myOtherRealm-copy:

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "iPlanetDirectoryPro: AQIC5w..." \
 --data '{
      "from": {
          "application": "iPlanetAMWebAgentService"
      },
      "to": {
          "realm": "/myOtherRealm",
          "namePostfix": "-copy"
      },
      "resourceTypeMapping": {
          "ccb50c1a-206d-4946-9106-4164e8f2b35b": "616b3d02-7a8d-4422-b6a7-174f62afd065"
      }

 }' \
 https://openam.example.com:8443/openam/json/realms/root/realms/myRealm/policies?_action
    =copy
{
    "name":"myNewPolicy-copy",
    "active":true,
    "description":"",
    "actionValues":{},
    "applicationName":"iPlanetAMWebAgentService",
    "resources":["*://*:*/*"],"subject":{"type":"NONE"},
    "resourceTypeUuid":"616b3d02-7a8d-4422-b6a7-174f62afd065",
    "lastModifiedBy":"id=amadmin,ou=user,dc=example,dc=com",
    "lastModifiedDate":"2015-12-21T20:01:42.410Z",
    "createdBy":"id=amadmin,ou=user,dc=example,dc=com",
    "creationDate":"2015-12-21T20:01:42.410Z"
}

2.2.7. Importing and Exporting XACML 3.0

OpenAM supports the ability to export policies to eXtensible Access Control Markup Language (XACML) 3.0-based formatted policy sets through its /xacml/policies REST endpoint. You can also import XACML 3.0 policy sets back into OpenAM by using the same endpoint. The endpoint's functionally is identical to that of the ssoadm create-xacml and ssoadm list-xacml commands. For more information, see "Importing and Exporting Policies".

Note

OpenAM can only import XACML 3.0 policy sets that were either created by an OpenAM instance, or that have had minor manual modifications, due to the reuse of some XACML 3.0 parameters for non-standard information.

When exporting OpenAM policies to XACML 3.0 policy sets, OpenAM maps its policies to XACML 3.0 policy elements. The mappings are as follows:

Policies to XACML Mappings
OpenAM PolicyXACML Policy
Policy NamePolicy ID
DescriptionDescription
Current Time (yyyy.MM.dd.HH.mm.ss.SSS)Version
xacml rule targetentitlement excluded resource names
Rule Deny OverridesRule Combining Algorithm ID

Any of:

  • Entitlement Subject

  • Resource Names

  • Policy Set Names

  • Action Values

Target

Any of:

  • Policy Set Name

  • Entitlement Name

  • Privilege Created By

  • Privilege Modified By

  • Privilege Creation Date

  • Privilege Last Modification Date

Variable Definitions
Single Level Permit/Deny Actions converted to Policy Rules Rules

Note

XACML obligation is not supported. Also, only one XACML match is defined for each privilege action, and only one XACML rule for each privilege action value.

2.2.7.1. Exporting to XACML

OpenAM supports exporting policies into XACML 3.0 format. OpenAM only exports a policy set that contains policy definitions. No other types can be included in the policy set, such as sub-policy sets or rules. The policy set mapping is as follows:

Policy Set Mappings
OpenAMXACML
Realm:<timestamp>(yyyy.MM.dd.HH.mm.ss.SSS)PolicySet ID
Current Time (yyyy.MM.dd.HH.mm.ss.SSS)Version
Deny OverridesPolicy Combining Algorithm ID
No targets definedTarget

The export service is accessible at the /xacml/policies endpoint using a HTTP GET request at the following endpoint for the root realm or a specific realm:

http://openam.example.com:8080/openam/xacml/policies
http://openam.example.com:8080/openam/xacml/{realm}/policies

where {realm} is the name of a specific realm

You can filter your XACML exports using query search filters. Note the following points about the search filters:

  • LDAP-based Searches. The search filters follow the standard guidelines for LDAP searches as they are applied to the entitlements index in the LDAP configuration backend, located at: ou=default,ou=OrganizationalConfig,ou=1.0,ou=sunEntitlementIndexes, ou=services,dc=openam,dc=forgerock,dc=org.

  • Search Filter Format. You can specify a single search filter or multiple filters in the HTTP URL parameters. The format for the search filter is as follows:

    [attribute name][operator][attribute value]

    If you specify multiple search filters, they are logically ANDed: the search results meet the criteria specified in all the search filters.

    XACML Export Search Filter Format
    ElementDescription
    Attribute Name

    The name of the attribute to be searched for. The only permissible values are: application (keyword for policy set), createdby, lastmodifiedby, creationdate, lastmodifieddate, name, description.

    Operator

    The type of comparison operation to perform.

    • = Equals (text)

    • < Less Than or Equal To (numerical)

    • > Greater Than or Equal To (numerical)

    Attribute Value

    The matching value. Asterisk wildcards are supported.


To Export Policies
  • Use the /xacml/policies endpoint to export the OpenAM entitlement policies into XACML 3.0 format. The following curl command exports the policies and returns the XACML response (truncated for display purposes).

    $ curl \
     --request GET \
     --header "iPlanetDirectoryPro: AQIC5..." \
     http://openam.example.com:8080/openam/xacml/policies
      
      
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <PolicySet xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
     PolicyCombiningAlgId="urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:deny-overrides"
     Version="2014.10.08.21.59.39.231" PolicySetId="/:2014.10.08.21.59.39.231">
     <Target/>
     <Policy RuleCombiningAlgId="urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:deny-overrides"
      Version="2014.10.08.18.01.03.626"
      PolicyId="Rockshop_Checkout_https://forgerock-rockshop.openrock.org:443/wp-login.php*?*">
      ...
To Export Policies with Search Filters
  1. Use the /xacml/policies endpoint to export the policies into XACML 3.0 format with a search filter. This command only exports policies that were created by "amadmin".

    $ curl \
     --request GET \
     --header "iPlanetDirectoryPro: AQIC5..." \
     http://openam.example.com:8080/openam/xacml/policies?filter=createdby=amadmin
  2. You can also specify more than one search filter by logically ANDing the filters as follows:

    $ curl \
     --request GET \
     --header "iPlanetDirectoryPro: AQIC5..." \
     http://openam.example.com:8080/openam/xacml/policies?filter=createdby=amadmin&
     filter=creationdate=135563832

2.2.7.2. Importing from XACML

OpenAM supports the import of XACML 3.0-based policy sets into OpenAM policies using the REST /xacml/policies endpoint. To test an import, OpenAM provides a dry-run feature that runs an import without saving the changes to the database. The dry-run feature provides a summary of the import so that you can troubleshoot any potential mismatches prior to the actual import.

You can import a XACML policy using an HTTP POST request for the root realm or a specific realm at the following endpoints:

http://openam.example.com:8080/openam/xacml/policies
http://openam.example.com:8080/openam/xacml/{realm}/policies

where {realm} is the name of a specific realm
To Import a XACML 3.0 Policy
  1. You can do a dry run using the dryrun=true query to test the import. The dry-run option outputs in JSON format and displays the status of each import policy, where "U" indicates "Updated"; "A" for "Added". The dry-run does not actually update to the database. When you are ready for an actual import, you need to re-run the command without the dryrun=true query.

    $ curl \
     --request POST \
     --header "Content-Type: application/xml" \
     --header "iPlanetDirectoryPro: AQIC5..." \
     --data @xacml-policy.xml \
     http://openam.example.com:8080/openam/xacml/policies?dryrun=true
    [
     {
       "status":"A",
       "name":"aNewPolicy"
     },
     {
       "status":"U",
       "name":"anExistingPolicy"
     },
     {
       "status":"U",
       "name":"anotherExistingPolicy"
     }
    ]
  2. Use the /xacml/policies endpoint to import a XACML policy:

    $ curl \
     --request POST \
     --header "Content-Type: application/xml" \
     --header "iPlanetDirectoryPro: AQIC5..." \
     --data @xacml-policy.xml \
     http://openam.example.com:8080/openam/xacml/policies

Tip

You can import a XACML policy into a realm as follows:

$ curl \
 --request POST \
 --header "Content-Type: application/xml" \
 --header "iPlanetDirectoryPro: AQIC5..." \
 --data @xacml-policy.xml \
 http://openam.example.com:8080/openam/xacml/{realm}/policies

2.2.8. Managing Environment Condition Types

Environment condition types describe the JSON representation of environment conditions that you can use in policy definitions.

OpenAM provides the conditiontypes REST endpoint for the following:

Environment condition types are server-wide, and do not differ by realm. Hence the URI for the condition types API does not contain a realm component, but is /json/conditiontypes.

Environment condition types are represented in JSON and take the following form. Environment condition types are built from standard JSON objects and values (strings, numbers, objects, arrays, true, false, and null).

{
    "title": "IPv4",
    "logical": false,
    "config": {
        "type": "object",
        "properties": {
            "startIp": {
                "type": "string"
            },
            "endIp": {
                "type": "string"
            },
            "dnsName": {
                "type": "array",
                "items": {
                    "type": "string"
                }
            }
        }
    }
}

Notice that the environment condition type has a title, a "logical" field that indicates whether the type is a logical operator or takes a predicate, and a configuration specification. The configuration specification in this case indicates that an IPv4 environment condition has two properties, "startIp" and "endIp", that each take a single string value, and a third property, "dnsName," that takes an array of string values. In other words, a concrete IP environment condition specification without a DNS name constraint could be represented in a policy definition as in the following example:

{
   "type": "IPv4",
   "startIp": "127.0.0.1",
   "endIp": "127.0.0.255"
}

The configuration is what differs the most across environment condition types. The NOT condition, for example, takes a single condition object as the body of its configuration.

{
  "title" : "NOT",
  "logical" : true,
  "config" : {
    "type" : "object",
    "properties" : {
      "condition" : {
        "type" : "object",
        "properties" : {
        }
      }
    }
  }
}

The concrete NOT condition therefore takes the following form.

{
    "type": "NOT",
    "condition": {
        ...
    }
}

The OR condition takes an array of conditions.

{
  "title" : "OR",
  "logical" : true,
  "config" : {
    "type" : "object",
    "properties" : {
      "conditions" : {
        "type" : "array",
        "items" : {
          "type" : "any"
        }
      }
    }
  }
}

A corresponding concrete OR condition thus takes the following form.

{
    "type": "OR",
    "conditions": [
        {
            ...
        },
        {
            ...
        },
        ...
    ]
}

2.2.8.1. Querying Environment Condition Types

To list all environment condition types, perform an HTTP GET to the /json/conditiontypes endpoint, with a _queryFilter parameter set to true.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/conditiontypes?_queryFilter=true
 {
    "result" : [
        {
            "title": "IPv4",
            "logical": false,
            "config": {
                "type": "object",
                "properties": {
                    "startIp": {
                        "type": "string"
                    },
                    "endIp": {
                        "type": "string"
                    },
                    "dnsName": {
                        "type": "array",
                        "items": {
                            "type": "string"
                        }
                    }
                }
            }
        },
        {
            "title": "NOT",
            "logical": true,
            "config": {
                "type": "object",
                "properties": {
                    "condition": {
                        "type": "object",
                        "properties": { }
                    }
                }
            }
        },
        {...},
        {...},
        {...}
    ],
    "resultCount" : 18,
    "pagedResultsCookie" : null,
    "remainingPagedResults" : 0
}

Additional query strings can be specified to alter the returned results. For more information, see "Query".

2.2.8.2. Reading a Specific Environment Condition Type

To read an individual environment condition type, perform an HTTP GET to the /json/conditiontypes endpoint, and specify the environment condition type name in the URL.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/conditiontypes/IPv4
{
  "title" : "IPv4",
  "logical" : false,
  "config" : {
    "type" : "object",
    "properties" : {
      "startIp" : {
        "type" : "string"
      },
      "endIp" : {
        "type" : "string"
      },
      "dnsName" : {
        "type" : "array",
        "items" : {
          "type" : "string"
        }
      }
    }
  }
}

2.2.9. Managing Subject Condition Types

Subject condition types describe the JSON representation of subject conditions that you can use in policy definitions.

OpenAM provides the subjecttypes REST endpoint for the following:

Environment condition types are server-wide, and do not differ by realm. Hence the URI for the condition types API does not contain a realm component, but is /json/subjecttypes.

Subject condition types are represented in JSON and take the following form. Subject condition types are built from standard JSON objects and values (strings, numbers, objects, arrays, true, false, and null).

{
    "title" : "Identity",
    "logical" : false,
    "config" : {
        "type" : "object",
        "properties" : {
            "subjectValues" : {
                "type" : "array",
                "items" : {
                    "type" : "string"
                }
            }
        }
    }
}

Notice that the subject type has a title, a "logical" field that indicates whether the type is a logical operator or takes a predicate, and a configuration specification. The configuration specification in this case indicates that an Identity subject condition has one property, "subjectValues", which takes an array of string values. In other words, a concrete Identity subject condition specification is represented in a policy definition as in the following example:

{
   "type": "Identity",
   "subjectValues": [
       "uid=scarter,ou=People,dc=example,dc=com"
   ]
}

The configuration is what differs the most across subject condition types. The AND condition, for example, takes an array of subject condition objects as the body of its configuration.

{
    "title" : "AND",
    "logical" : true,
    "config" : {
        "type" : "object",
        "properties" : {
            "subjects" : {
                "type" : "array",
                "items" : {
                    "type" : "any"
                }
            }
        }
    }
}

The concrete AND subject condition therefore takes the following form.

{
    "type": "AND",
    "subject": [
      {...},
      {...},
      {...},
      {...}
    ]
}

2.2.9.1. Querying Subject Condition Types

To list all environment condition types, perform an HTTP GET to the /json/subjecttypes endpoint, with a _queryFilter parameter set to true.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/subjecttypes?_queryFilter=true
 {
    "result" : [
        {
            "title": "JwtClaim",
            "logical": false,
            "config": {
                "type": "object",
                "properties": {
                    "claimName": {
                        "type": "string"
                    },
                    "claimValue": {
                        "type": "string"
                    }
                }
            }
        },
        {
            "title": "NOT",
            "logical": true,
            "config": {
                "type": "object",
                "properties": {
                    "subject": {
                        "type": "object",
                        "properties": { }
                    }
                }
            }
        },
        {...},
        {...},
        {...}
    ],
    "resultCount" : 5,
    "pagedResultsCookie" : null,
    "remainingPagedResults" : 0
}

Additional query strings can be specified to alter the returned results. For more information, see "Query".

2.2.9.2. Reading a Specific Subject Condition Type

To read an individual subject condition type, perform an HTTP GET to the /json/subjecttypes endpoint, and specify the subject condition type name in the URL.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/subjecttypes/Identity
{
    "title" : "Identity",
    "logical" : false,
    "config" : {
        "type" : "object",
        "properties" : {
            "subjectValues" : {
                "type" : "array",
                "items" : {
                    "type" : "string"
                }
            }
        }
    }
}

2.2.10. Managing Subject Attributes

When you define a policy subject condition, the condition can depend on values of subject attributes stored in a user's profile. The list of possible subject attributes that you can use depends on the LDAP User Attributes configured for the Identity data store where OpenAM looks up the user's profile.

OpenAM provides the subjectattributes REST endpoint for the following:

Subject attributes derive from the list of LDAP user attributes configured for the Identity data store. For more information, see "Setting Up Identity Data Stores" in the Setup and Maintenance Guide.

2.2.10.1. Querying Subject Attributes

To list all subject attributes, perform an HTTP GET to the /json/subjectattributes endpoint, with a _queryFilter parameter set to true.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/subjectattributes/?_queryFilter=true

{
    "result" : [
        "sunIdentityServerPPInformalName",
        "sunIdentityServerPPFacadeGreetSound",
        "uid",
        "manager",
        "sunIdentityServerPPCommonNameMN",
        "sunIdentityServerPPLegalIdentityGender",
        "preferredLocale",
        "...",
        "...",
        "..."
    ],
    "resultCount": 87,
    "pagedResultsCookie": null,
    "remainingPagedResults": 0
}

Note that no pagination cookie is set and the subject attribute names are all returned as part of the "result" array.

2.2.11. Managing Decision Combiners

Decision combiners describe how to resolve policy decisions when multiple policies apply.

OpenAM provides the decisioncombiners REST endpoint for the following:

Decision combiners are server-wide, and do not differ by realm. Hence the URI for the condition types API does not contain a realm component, but is /json/decisioncombiners.

2.2.11.1. Querying Decision Combiners

To list all decision combiners, perform an HTTP GET to the /json/decisioncombiners endpoint, with a _queryFilter parameter set to true.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/decisioncombiners?_queryFilter=true
{
    "result": [
        {
            "title": "DenyOverride"
        }
    ],
    "resultCount": 1,
    "pagedResultsCookie": null,
    "remainingPagedResults": 0
}

Additional query strings can be specified to alter the returned results. For more information, see "Query".

2.2.11.2. Reading a Specific Decision Combiner

To view an individual decision combiner, perform an HTTP GET on its resource.

To read an individual decision combiner, perform an HTTP GET to the /json/decisioncombiners endpoint, and specify the decision combiner name in the URL.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
 --header "iPlanetDirectoryPro: AQIC5..." \
 https://openam.example.com:8443/openam/json/realms/root/decisioncombiners/DenyOverride
{
  "title" : "DenyOverride"
}

Chapter 3. Customizing Authorization

This chapter describes how to customize policy evaluation by writing a policy plug-in and by scripting a customized policy condition.

3.1. Customizing Policy Evaluation With a Plug-In

OpenAM policies let you restrict access to resources based both on identity and group membership, and also on a range of conditions including session age, authentication chain or module used, authentication level, realm, session properties, IP address and DNS name, user profile content, resource environment, date, day, time of day, and time zone. Yet, some deployments require further distinctions for policy evaluation. This section explains how to customize policy evaluation for deployments with particular requirements not met by built-in OpenAM functionality.

This section shows how to build and use a custom policy plugin that implements a custom subject condition, a custom environment condition, and a custom resource attribute.

3.1.1. About the Sample Plugin

The OpenAM policy framework lets you build plugins that extend subject conditions, environment conditions, and resource attributes.

For information on downloading and building AM sample source code, see How do I access and build the sample code provided for OpenAM 12.x, 13.x and AM (All versions)? in the Knowledge Base.

Get a local clone so that you can try the sample on your system. In the sources, you find the following files under the /path/to/openam-source/openam-samples/policy-evaluation-plugin directory:

pom.xml

Apache Maven project file for the module

This file specifies how to build the sample policy evaluation plugin, and also specifies its dependencies on OpenAM components.

src/main/java/org/forgerock/openam/examples/SampleAttributeType.java

Extends the com.sun.identity.entitlement.ResourceAttribute interface, and shows an implementation of a resource attribute provider to send an attribute with the response.

src/main/java/org/forgerock/openam/examples/SampleConditionType.java

Extends the com.sun.identity.entitlement.EntitlementCondition interface, and shows an implementation of a condition that is the length of the user name.

A condition influences whether the policy applies for a given access request. If the condition is fulfilled, then OpenAM includes the policy in the set of policies to evaluate in order to respond to a policy decision request.

src/main/java/org/forgerock/openam/examples/SampleSubjectType.java

Extends the com.sun.identity.entitlement.EntitlementSubject interface, and shows an implementation that defines a user to whom the policy applies.

A subject, like a condition, influences whether the policy applies. If the subject matches in the context of a given access request, then the policy applies.

src/main/java/org/forgerock/openam/examples/SampleEntitlementModule.java, src/main/resources/META-INF/services/org.forgerock.openam.entitlement.EntitlementModule

These files serve to register the plugin with OpenAM.

The Java class, SampleEntitlementModule, implements the org.forgerock.openam.entitlement.EntitlementModule interface. In the sample, this class registers SampleAttribute, SampleCondition, and SampleSubject.

The services file, org.forgerock.openam.entitlement.EntitlementModule, holds the fully qualified class name of the EntitlementModule that registers the custom implementations. In this case, org.forgerock.openam.entitlement.EntitlementModule.

3.1.2. Building the Sample Plugin

Follow the steps in this procedure to build the sample plugin:

To Build the Sample Plugin
  1. If you have not already done so, download and build the samples.

    For information on downloading and building AM sample source code, see How do I access and build the sample code provided for OpenAM 12.x, 13.x and AM (All versions)? in the Knowledge Base.

  2. Check out the ${sourceBranch} branch of the OpenAM source.

  3. Build the module using Apache Maven:

    $ cd /path/to/openam-source/openam-samples
    $ cd policy-evaluation-plugin
    $ mvn install
    [INFO] Scanning for projects...
    [INFO]
    [INFO] ------------------------------------------------------------------------
    [INFO] Building policy-evaluation-plugin 5.0.0-21
    [INFO] ------------------------------------------------------------------------
    [INFO]
    [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @
    [INFO] policy-evaluation-plugin ---
    
    ...
    
    [INFO] Building jar: .../target/policy-evaluation-plugin-5.0.0-21.jar
    [INFO]
    
    ...
    
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 5.264 s
    [INFO] Finished at: 2016-05-11T19:39:23+02:00
    [INFO] Final Memory: 32M/85M
    [INFO] ------------------------------------------------------------------------
  4. Copy the .jar to the WEB-INF/lib directory where you deployed OpenAM:

    $ cp target/*.jar /path/to/tomcat/webapps/openam/WEB-INF/lib/
  5. Edit the /path/to/tomcat/webapps/openam/XUI/locales/en/translation.json file to update the user interface to include the custom subject and environment conditions:

    1. Locate the line that contains the following text:

      "subjectTypes": {

    2. Insert the following text after the line you located in the previous step:

      "SampleSubject": {
          "title": "Sample Subject",
          "props": {
              "name": "Name"
          }
      },

    3. Locate the line that contains the following text:

      "conditionTypes": {

    4. Insert the following text after the line you located in the previous step:

      "SampleCondition": {
          "title": "Sample Condition",
          "props": {
              "nameLength": "Minimum username length"
          }
      },

  6. If you require additional translations under /path/to/tomcat/webapps/openam/XUI/locales, modify other translation.json files as needed.

  7. Clear your browser's cache and restart your browser.

    Clearing the cache and refreshing the browser is required when you modify the translation.json file.

  8. Restart OpenAM or the container in which it runs.

3.1.3. Adding Custom Policy Implementations to Existing Policy Sets

In order to use your custom policy in existing policy sets, you must update the policy sets. Note that you cannot update a policy set that already has policies configured. When there are already policies configured for a policy set, you must instead first delete the policies, and then update the policy set.

Update the iPlanetAMWebAgentService policy set in the top level realm of a fresh installation. First, authenticate to OpenAM as the amadmin user:

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "X-OpenAM-Username: amadmin" \
 --header "X-OpenAM-Password: password" \
 --data "{}" \
 https://openam.example.com:8443/openam/json/realms/root/authenticate
{"tokenId":"AQIC5wM2...","successUrl":"/openam/console"}

Then update the iPlanetAMWebAgentService policy set by adding the SampleSubject subject condition and the SampleCondition environment condition:

$ curl \
 --request PUT \
 --header "iPlanetDirectoryPro: AQIC5wM2..." \
 --header "Content-Type: application/json" \
 --data '{
    "name": "iPlanetAMWebAgentService",
    "conditions": [
        "LEAuthLevel",
        "Script",
        "AuthenticateToService",
        "SimpleTime",
        "AMIdentityMembership",
        "OR",
        "IPv6",
        "IPv4",
        "SessionProperty",
        "AuthScheme",
        "AuthLevel",
        "NOT",
        "AuthenticateToRealm",
        "AND",
        "ResourceEnvIP",
        "LDAPFilter",
        "OAuth2Scope",
        "Session",
        "SampleCondition"
    ],
    "subjects": [
        "NOT",
        "OR",
        "JwtClaim",
        "AuthenticatedUsers",
        "AND",
        "Identity",
        "NONE",
        "SampleSubject"
    ],
    "applicationType": "iPlanetAMWebAgentService",
    "entitlementCombiner": "DenyOverride"
   }' https://openam.example.com:8443/openam/json/realms/root/applications/iPlanetAMWebAgentService

3.1.4. Trying the Sample Subject and Environment Conditions

Using the AM console, add a policy to the iPlanetAMWebAgentService policy set in the top level realm that allows HTTP GET access for URLs based on the template http://www.example.com:80/* and uses the custom subject and environment conditions.

Create the policy with the following properties:

Sample Policy Properties
PropertyValue
NameSample Policy
Resource TypeURL
Resources Use the *://*:*/*resource template to specify the resource http://www.example.com:80/*.
ActionsAllow GET
Subject ConditionsAdd a subject condition of type Sample Subject and a name of demo so that the demo user is the only user who can access the resource.
Environment ConditionsAdd an environment condition of type Sample Condition and a minimum username length of 4 so that only users with a username length of 4 characters or greater can access the resource.

With the policy in place, authenticate both as a user who can request policy decisions and also as a user trying to access a resource. Both of these calls return tokenId values for use in the policy decision request.

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "X-OpenAM-Username: amadmin" \
 --header "X-OpenAM-Password: password" \
 --data "{}" \
 https://openam.example.com:8443/openam/json/realms/root/authenticate

{"tokenId":"AQIC5wM2LY4Sfcw...","successUrl":"/openam/console"}

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "X-OpenAM-Username: demo" \
 --header "X-OpenAM-Password: changeit" \
 --data "{}" \
 https://openam.example.com:8443/openam/json/realms/root/authenticate

{"tokenId":"AQIC5wM2LY4Sfcy...","successUrl":"/openam/console"}

Use the administrator tokenId as the header of the policy decision request, and the user tokenId as the subject ssoToken value.

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "iPlanetDirectoryPro: AQIC5wM2LY4Sfcw..." \
 --data '{
    "subject": {
      "ssoToken": "AQIC5wM2LY4Sfcy..."},
    "resources": [
        "http://www.example.com:80/index.html"
    ],
    "application": "iPlanetAMWebAgentService"
 }' \
 https://openam.example.com:8443/openam/json/realms/root/policies?_action=evaluate

[
   {
       "resource": "http://www.example.com:80/index.html",
       "actions": {
           "GET": true
       },
       "attributes": {},
       "advices": {}
   }
]

Notice that the actions returned from the policy evaluation call are set in accordance with the policy.

3.1.5. Trying the Sample Resource Attributes

The sample custom policy plugin can have OpenAM return an attribute with the policy decision. In order to make this work, list the resource type for the URL resource type to obtain its UUID, and then update your policy to return a test attribute:

$ curl \
 --request GET \
 --header "iPlanetDirectoryPro: AQIC5wM2..." \
 https://openam.example.com:8443/openam/json/realms/root/resourcetypes?_queryFilter=name%20eq%20%22URL%22
{
  "result":[
    {
      "uuid":"URL-resource-type-UUID",
      "name":"URL",
      "description":"The built-in URL Resource Type available to OpenAM Policies.",
      "patterns":["*://*:*/*","*://*:*/*?*"],
      ...
    }
  ],
  "resultCount":1,
  "pagedResultsCookie":null,
  "totalPagedResultsPolicy":"NONE",
  "totalPagedResults":-1,
  "remainingPagedResults":0
}

$ curl \
 --request PUT \
 --header "iPlanetDirectoryPro: AQIC5wM2LY4Sfcw..." \
 --header "Content-Type: application/json" \
 --data '{
    "name": "Sample Policy",
    "active": true,
    "description": "Try sample policy plugin",
    "resourceTypeUuid": "URL-resource-type-UUID",
    "resources": [
        "http://www.example.com:80/*"
    ],
    "applicationName": "iPlanetAMWebAgentService",
    "actionValues": {
        "GET": true
    },
    "subject": {
        "type": "SampleSubject",
        "name": "demo"
    },
    "condition": {
        "type": "SampleCondition",
        "nameLength": 4
    },
    "resourceAttributes": [
        {
            "type": "SampleAttribute",
            "propertyName": "test"
        }
    ]
}' http://openam.example.com:8088/openam/json/policies/Sample%20Policy

When you now request the same policy decision as before, OpenAM returns the test attribute that you configured in the policy.

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "iPlanetDirectoryPro: AQIC5wM2LY4Sfcw..." \
 --data '{
    "subject": {
      "ssoToken": "AQIC5wM2LY4Sfcy..."},
    "resources": [
        "http://www.example.com:80/index.html"
    ],
    "application": "iPlanetAMWebAgentService"
 }' \
 http://openam.example.com:8080/openam/json/realms/root/policies?_action=evaluate

[
    {
        "resource": "http://www.example.com/profile",
        "actions": {
            "GET": true
        },
        "attributes": {
            "test": [
                "sample"
            ]
        },
        "advices": {}
    }
]

3.1.6. Extending the ssoadm Classpath

After customizing your OpenAM deployment to use policy evaluation plugins, inform ssoadm users to add the jar file containing the plugins to the classpath before running policy management subcommands.

To add a jar file to the ssoadm classpath, set the CLASSPATH environment variable before running the ssoadm command.

$ export CLASSPATH=/path/to/jarfile:$CLASSPATH
$ ssoadm ...

3.2. Scripting a Policy Condition

This section demonstrates how to use the sample policy condition script as part of an authorization policy. To examine the contents of the sample policy condition script in the AM console browse to Realms > Top Level Realm > Scripts, and then click Scripted Policy Condition.

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

For general information about scripting in OpenAM, see "About Scripting".

For information about APIs available for use when scripting policy conditions, see the following sections:

3.2.1. Preparing

OpenAM 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.

The procedures in this section are:

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 OpenAM administrator, for example amadmin.

  2. Click Realms > Top Level Realm > Subjects.

  3. On the User tab, click the demo user.

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

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

To Allow the Demo User to Evaluate a Policy

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

  1. Log in as an OpenAM administrator, for example amadmin.

  2. Click Realms > Top Level Realm > Subjects.

  3. On the Group tab, click New, enter an ID for the group, such as policyEval, and then click OK.

  4. On the User tab:

    1. Click the demo user.

    2. Click the Group tab.

    3. In the Available box, select the group created in step 3, and then click Add.

    4. Click Save.

  5. Click Realms > Top Level Realm > Privileges.

  6. Click the group created in step 3, for example policyEval.

  7. On the Privileges page, select Read and write access to all realm and policy properties.

  8. Click Save.

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 OpenAM administrator, for example amadmin.

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

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

  4. On the Default Policy Set page, click 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. Click Add.

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

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

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

      6. Click Add.

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

      7. Click 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. Click Save Changes.

    4. Configure subjects to which the policy applies:

      1. Select the Subjects tab.

      2. Click the edit icon—the pencil.

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

      4. Click 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. Click Save Changes.

    5. Configure environments in which the policy applies:

      1. Select the Environments tab.

      2. Click 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. Click 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. Click Save Changes.

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

To Enable Message-level Logging for Policy Evaluation

The default policy condition script writes to the debug logs at the message level. Message-level debug logging is not enabled for policy evaluation by default.

This section shows how to enable message-level debug logging for policy evaluation, so that logger output from the default policy condition script can be viewed in the Entitlement debug log.

  1. Log in as an OpenAM administrator, for example amadmin.

  2. Visit the Debug.jsp page, for example: https://openam.example.com:8443/openam/Debug.jsp.

  3. In the Debug instances drop-down, select Entitlement.

  4. In the Level drop-down, choose the debug level required. In this example, select Message.

    Use the Debug.jsp page to enable message-level debug logging.
  5. Click Submit, and on the summary page that appears, click Confirm.

    Message-level debug logging is now enabled for policy evaluation.

3.2.2. Trying the Default Policy Condition Script

This section demonstrates using a policy that contains 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 "X-OpenAM-Username: demo" \
     --header "X-OpenAM-Password: changeit" \
     https://openam.example.com:8443/openam/json/realms/root/authenticate
    {
         "tokenId": "AQIC5wM2...",
         "successUrl": "/openam/console"
    }
  2. Send an evaluation request to the policies endpoint, using the SSO token of the demo user in the iPlanetDirectoryPro header.

    In the JSON data, set the subject property to also be the SSO token of the demo user. In the resources property, include a URL that resides on a server in the same country as the address set for the demo user. In the environment property, include an IP address that is also based in the same country as the user and the resource. The example below uses the ForgeRock Community web site URL and an IP address from a ForgeRock office, both located in the United States:

    curl \
     --request POST \
     --header "Content-Type: application/json" \
     --header "iPlanetDirectoryPro: AQIC5wM2..." \
     --data '{
        "resources": [
            "http://www.forgerock.org:80/index.html"
        ],
        "application": "iPlanetAMWebAgentService",
        "subject": { "ssoToken": "AQIC5wM2..."},
        "environment": {
            "IP": [
                "38.99.39.210"
            ]
        }
    }' \
    https://openam.example.com:8443/openam/json/realms/root/policies?_action=evaluate
    [
      {
        "advices": {},
        "ttl": 9223372036854775807,
        "resource": "http://www.forgerock.org:80/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 OpenAM 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 -X POST \
    -H "Content-Type: application/json" \
    -H "iPlanetDirectoryPro: AQIC5wM2..." \
    -d '{
        "resources": [
            "http://www.forgerock.fr:80/index.html"
        ],
        "application": "iPlanetAMWebAgentService",
        "subject": { "ssoToken": "AQIC5wM2..."},
        "environment": {
            "IP": [
                "38.99.39.210"
            ]
        }
    }' \
    'https://openam.example.com:8443/openam/json/realms/root/policies?_action=evaluate'
    [
        {
            "advices": {},
            "ttl": 9223372036854775807,
            "resource": "http://www.forgerock.fr:80/index.html",
            "actions": {},
            "attributes": {}
        }
    ]

Chapter 4. Reference

This reference section covers settings and the scripting API relating to authorization in AM.

4.1. Policy Configuration

amster type ID: policyconfiguration

4.1.1. Global Attributes

The following settings appear on the Global Attributes tab:

Resource Comparator

OpenAM uses resource comparators to match resources specified in policy rules. When setting comparators on the command line, separate fields with | characters.

Default value:

serviceType=iPlanetAMWebAgentService|class=com.sun.identity.policy.plugins.HttpURLResourceName|wildcard=*|oneLevelWildcard=-*-|delimiter=/|caseSensitive=false
serviceType=sunIdentityServerDiscoveryService|class=com.sun.identity.policy.plugins.PrefixResourceName|wildcard=*|oneLevelWildcard=-*-|delimiter=;|caseSensitive=false

amster data attribute: resourceComparators

Continue Evaluation on Deny Decision

If no, then OpenAM stops evaluating policy as soon as it reaches a deny decision.

Default value: false

amster data attribute: continueEvaluationOnDeny

Realm Alias Referrals

If yes, then OpenAM allows creation of policies for HTTP and HTTPS resources whose FQDN matches the DNS alias for the realm even when no referral policy exists.

Default value: false

amster data attribute: realmAliasReferrals

4.1.2. Realm Defaults

The following settings appear on the Realm Defaults tab:

Primary LDAP Server

Configuration directory server host:port that OpenAM searches for policy information.

Format: local server name | host name:port

Multiple entries must be prefixed by local server name.

Default value: openam.example.com:50389

amster data attribute: ldapServer

LDAP Users Base DN

Base DN for LDAP Users subject searches.

Default value: dc=openam,dc=forgerock,dc=org

amster data attribute: usersBaseDn

OpenAM Roles Base DN

Base DN for OpenAM Roles searches.

Default value: dc=openam,dc=forgerock,dc=org

amster data attribute: rolesBaseDn

LDAP Bind DN

Bind DN to connect to the directory server for policy information.

Default value: cn=Directory Manager

amster data attribute: bindDn

LDAP Bind Password

Bind password to connect to the directory server for policy information.

amster data attribute: bindPassword

LDAP Organization Search Filter

Search filter to match organization entries.

Default value: (objectclass=sunismanagedorganization)

amster data attribute: realmSearchFilter

LDAP Users Search Filter

Search filter to match user entries.

Default value: (objectclass=inetorgperson)

amster data attribute: usersSearchFilter

LDAP Users Search Scope

Search scope to find user entries.

The possible values for this property are:

SCOPE_BASE
SCOPE_ONE
SCOPE_SUB

Default value: SCOPE_SUB

amster data attribute: usersSearchScope

OpenAM Roles Search Scope

Search scope to find OpenAM roles entries.

The possible values for this property are:

SCOPE_BASE
SCOPE_ONE
SCOPE_SUB

Default value: SCOPE_SUB

amster data attribute: rolesSearchScope

LDAP Users Search Attribute

Naming attribute for user entries.

Default value: uid

amster data attribute: usersSearchAttribute

Maximum Results Returned from Search

Search limit for LDAP searches.

Default value: 100

amster data attribute: maximumSearchResults

Search Timeout

Time after which OpenAM returns an error for an incomplete search, in seconds.

Default value: 5

amster data attribute: searchTimeout

LDAP SSL/TLS

If enabled, OpenAM connects securely to the directory server. This requires that you install the directory server certificate.

Default value: false

amster data attribute: sslEnabled

LDAP Connection Pool Minimum Size

Minimum number of connections in the pool.

Default value: 1

amster data attribute: connectionPoolMinimumSize

LDAP Connection Pool Maximum Size

Maximum number of connections in the pool.

Default value: 10

amster data attribute: connectionPoolMaximumSize

Subjects Result Time to Live

Maximum time that OpenAM caches a subject result for evaluating policy requests, in minutes. A value of 0 prevents OpenAM from caching subject evaluations for policy decisions.

Default value: 10

amster data attribute: subjectsResultTTL

User Alias

If enabled, OpenAM can evaluate policy for remote users aliased to local users.

Default value: false

amster data attribute: userAliasEnabled

4.2. Authorization API Functionality

This section covers functionality available when scripting authorization using the policy condition script context type.

4.2.1. 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.


4.2.2. 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.


4.2.3. 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. For example, AuthLevel.


4.2.4. 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.


Appendix A. About the REST API

This appendix shows how to use the RESTful interfaces for direct integration between web client applications and AM.

A.1. Introducing REST

Representational State Transfer (REST) is an architectural style that sets certain constraints for designing and building large-scale distributed hypermedia systems.

As an architectural style, REST has very broad applications. The designs of both HTTP 1.1 and URIs follow RESTful principles. The World Wide Web is no doubt the largest and best known REST application. Many other web services also follow the REST architectural style. Examples include OAuth 2.0, OpenID Connect 1.0, and User-Managed Access (UMA).

The ForgeRock Common REST (CREST) API applies RESTful principles to define common verbs for HTTP-based APIs that access web resources and collections of web resources.

Interface Stability: Evolving

Most native OpenAM REST APIs use the CREST verbs. (In contrast, OAuth 2.0, OpenID Connect 1.0 and UMA APIs follow their respective standards.)

A.2. About ForgeRock Common REST

ForgeRock® Common REST is a common REST API framework. It works across the ForgeRock platform to provide common ways to access web resources and collections of resources. Adapt the examples in this section to your resources and deployment.

A.2.1. Common REST Resources

Servers generally return JSON-format resources, though resource formats can depend on the implementation.

Resources in collections can be found by their unique identifiers (IDs). IDs are exposed in the resource URIs. For example, if a server has a user collection under /users, then you can access a user at /users/user-id. The ID is also the value of the _id field of the resource.

Resources are versioned using revision numbers. A revision is specified in the resource's _rev field. Revisions make it possible to figure out whether to apply changes without resource locking and without distributed transactions.

A.2.2. Common REST Verbs

The Common REST APIs use the following verbs, sometimes referred to collectively as CRUDPAQ. For details and HTTP-based examples of each, follow the links to the sections for each verb.

Create

Add a new resource.

This verb maps to HTTP PUT or HTTP POST.

For details, see "Create".

Read

Retrieve a single resource.

This verb maps to HTTP GET.

For details, see "Read".

Update

Replace an existing resource.

This verb maps to HTTP PUT.

For details, see "Update".

Delete

Remove an existing resource.

This verb maps to HTTP DELETE.

For details, see "Delete".

Patch

Modify part of an existing resource.

This verb maps to HTTP PATCH.

For details, see "Patch".

Action

Perform a predefined action.

This verb maps to HTTP POST.

For details, see "Action".

Query

Search a collection of resources.

This verb maps to HTTP GET.

For details, see "Query".

A.2.3. Common REST Parameters

Common REST reserved query string parameter names start with an underscore, _.

Reserved query string parameters include, but are not limited to, the following names:

_action
_api
_crestapi
_fields
_mimeType
_pageSize
_pagedResultsCookie
_pagedResultsOffset
_prettyPrint
_queryExpression
_queryFilter
_queryId
_sortKeys
_totalPagedResultsPolicy

Note

Some parameter values are not safe for URLs, so URL-encode parameter values as necessary.

Continue reading for details about how to use each parameter.

A.2.4. Common REST Extension Points

The action verb is the main vehicle for extensions. For example, to create a new user with HTTP POST rather than HTTP PUT, you might use /users?_action=create. A server can define additional actions. For example, /tasks/1?_action=cancel.

A server can define stored queries to call by ID. For example, /groups?_queryId=hasDeletedMembers. Stored queries can call for additional parameters. The parameters are also passed in the query string. Which parameters are valid depends on the stored query.

A.2.5. Common REST API Documentation

Common REST APIs often depend at least in part on runtime configuration. Many Common REST endpoints therefore serve API descriptors at runtime. An API descriptor documents the actual API as it is configured.

Use the following query string parameters to retrieve API descriptors:

_api

Serves an API descriptor that complies with the OpenAPI specification.

This API descriptor represents the API accessible over HTTP. It is suitable for use with popular tools such as Swagger UI.

_crestapi

Serves a native Common REST API descriptor.

This API descriptor provides a compact representation that is not dependent on the transport protocol. It requires a client that understands Common REST, as it omits many Common REST defaults.

Note

Consider limiting access to API descriptors in production environments in order to avoid unnecessary traffic.

To provide documentation in production environments, see "To Publish OpenAPI Documentation" instead.

To Publish OpenAPI Documentation

In production systems, developers expect stable, well-documented APIs. Rather than retrieving API descriptors at runtime through Common REST, prepare final versions, and publish them alongside the software in production.

Use the OpenAPI-compliant descriptors to provide API reference documentation for your developers as described in the following steps:

  1. Configure the software to produce production-ready APIs.

    In other words, the software should be configured as in production so that the APIs are identical to what developers see in production.

  2. Retrieve the OpenAPI-compliant descriptor.

    The following command saves the descriptor to a file, myapi.json:

    $ curl -o myapi.json endpoint?_api
        
  3. (Optional) If necessary, edit the descriptor.

    For example, you might want to add security definitions to describe how the API is protected.

    If you make any changes, then also consider using a source control system to manage your versions of the API descriptor.

  4. Publish the descriptor using a tool such as Swagger UI.

    You can customize Swagger UI for your organization as described in the documentation for the tool.

A.2.6. Create

There are two ways to create a resource, either with an HTTP POST or with an HTTP PUT.

To create a resource using POST, perform an HTTP POST with the query string parameter _action=create and the JSON resource as a payload. Accept a JSON response. The server creates the identifier if not specified:

POST /users?_action=create HTTP/1.1
Host: example.com
Accept: application/json
Content-Length: ...
Content-Type: application/json
{ JSON resource }
  

To create a resource using PUT, perform an HTTP PUT including the case-sensitive identifier for the resource in the URL path, and the JSON resource as a payload. Use the If-None-Match: * header. Accept a JSON response:

PUT /users/some-id HTTP/1.1
Host: example.com
Accept: application/json
Content-Length: ...
Content-Type: application/json
If-None-Match: *
{ JSON resource }
  

The _id and content of the resource depend on the server implementation. The server is not required to use the _id that the client provides. The server response to the create request indicates the resource location as the value of the Location header.

If you include the If-None-Match header, its value must be *. In this case, the request creates the object if it does not exist, and fails if the object does exist. If you include the If-None-Match header with any value other than *, the server returns an HTTP 400 Bad Request error. For example, creating an object with If-None-Match: revision returns a bad request error. If you do not include If-None-Match: *, the request creates the object if it does not exist, and updates the object if it does exist.

Parameters

You can use the following parameters:

_prettyPrint=true

Format the body of the response.

_fields=field[,field...]

Return only the specified fields in the body of the response.

The field values are JSON pointers. For example if the resource is {"parent":{"child":"value"}}, parent/child refers to the "child":"value".

A.2.7. Read

To retrieve a single resource, perform an HTTP GET on the resource by its case-sensitive identifier (_id) and accept a JSON response:

GET /users/some-id HTTP/1.1
Host: example.com
Accept: application/json
  
Parameters

You can use the following parameters:

_prettyPrint=true

Format the body of the response.

_fields=field[,field...]

Return only the specified fields in the body of the response.

The field values are JSON pointers. For example if the resource is {"parent":{"child":"value"}}, parent/child refers to the "child":"value".

_mimeType=mime-type

Some resources have fields whose values are multi-media resources such as a profile photo for example.

By specifying both a single field and also the mime-type for the response content, you can read a single field value that is a multi-media resource.

In this case, the content type of the field value returned matches the mime-type that you specify, and the body of the response is the multi-media resource.

The Accept header is not used in this case. For example, Accept: image/png does not work. Use the _mimeType query string parameter instead.

A.2.8. Update

To update a resource, perform an HTTP PUT including the case-sensitive identifier (_id) as the final element of the path to the resource, and the JSON resource as the payload. Use the If-Match: _rev header to check that you are actually updating the version you modified. Use If-Match: * if the version does not matter. Accept a JSON response:

PUT /users/some-id HTTP/1.1
Host: example.com
Accept: application/json
Content-Length: ...
Content-Type: application/json
If-Match: _rev
{ JSON resource }
  

When updating a resource, include all the attributes to be retained. Omitting an attribute in the resource amounts to deleting the attribute unless it is not under the control of your application. Attributes not under the control of your application include private and read-only attributes. In addition, virtual attributes and relationship references might not be under the control of your application.

Parameters

You can use the following parameters:

_prettyPrint=true

Format the body of the response.

_fields=field[,field...]

Return only the specified fields in the body of the response.

The field values are JSON pointers. For example if the resource is {"parent":{"child":"value"}}, parent/child refers to the "child":"value".

A.2.9. Delete

To delete a single resource, perform an HTTP DELETE by its case-sensitive identifier (_id) and accept a JSON response:

DELETE /users/some-id HTTP/1.1
Host: example.com
Accept: application/json
  
Parameters

You can use the following parameters:

_prettyPrint=true

Format the body of the response.

_fields=field[,field...]

Return only the specified fields in the body of the response.

The field values are JSON pointers. For example if the resource is {"parent":{"child":"value"}}, parent/child refers to the "child":"value".

A.2.10. Patch

To patch a resource, send an HTTP PATCH request with the following parameters:

  • operation

  • field

  • value

  • from (optional with copy and move operations)

You can include these parameters in the payload for a PATCH request, or in a JSON PATCH file. If successful, you'll see a JSON response similar to:

PATCH /users/some-id HTTP/1.1
Host: example.com
Accept: application/json
Content-Length: ...
Content-Type: application/json
If-Match: _rev
{ JSON array of patch operations }
  

PATCH operations apply to three types of targets:

  • single-valued, such as an object, string, boolean, or number.

  • list semantics array, where the elements are ordered, and duplicates are allowed.

  • set semantics array, where the elements are not ordered, and duplicates are not allowed.

ForgeRock PATCH supports several different operations. The following sections show each of these operations, along with options for the field and value:

A.2.10.1. Patch Operation: Add

The add operation ensures that the target field contains the value provided, creating parent fields as necessary.

If the target field is single-valued, then the value you include in the PATCH replaces the value of the target. Examples of a single-valued field include: object, string, boolean, or number.

An add operation has different results on two standard types of arrays:

  • List semantic arrays: you can run any of these add operations on that type of array:

    • If you add an array of values, the PATCH operation appends it to the existing list of values.

    • If you add a single value, specify an ordinal element in the target array, or use the {-} special index to add that value to the end of the list.

  • Set semantic arrays: The list of values included in a patch are merged with the existing set of values. Any duplicates within the array are removed.

As an example, start with the following list semantic array resource:

{
    "fruits" : [ "orange", "apple" ]
}

The following add operation includes the pineapple to the end of the list of fruits, as indicated by the - at the end of the fruits array.

{
    "operation" : "add",
    "field" : "/fruits/-",
    "value" : "pineapple"
}

The following is the resulting resource:

{
    "fruits" : [ "orange", "apple", "pineapple" ]
}

A.2.10.2. Patch Operation: Copy

The copy operation takes one or more existing values from the source field. It then adds those same values on the target field. Once the values are known, it is equivalent to performing an add operation on the target field.

The following copy operation takes the value from a field named mail, and then runs a replace operation on the target field, another_mail.

[
  {
     "operation":"copy",
     "from":"mail",
     "field":"another_mail"
  }
]

If the source field value and the target field value are configured as arrays, the result depends on whether the array has list semantics or set semantics, as described in "Patch Operation: Add".

A.2.10.3. Patch Operation: Increment

The increment operation changes the value or values of the target field by the amount you specify. The value that you include must be one number, and may be positive or negative. The value of the target field must accept numbers. The following increment operation adds 1000 to the target value of /user/payment.

[
  {
    "operation" : "increment",
    "field" : "/user/payment",
    "value" : "1000"
  }
]

Since the value of the increment is a single number, arrays do not apply.

A.2.10.4. Patch Operation: Move

The move operation removes existing values on the source field. It then adds those same values on the target field. It is equivalent to performing a remove operation on the source, followed by an add operation with the same values, on the target.

The following move operation is equivalent to a remove operation on the source field, surname, followed by a replace operation on the target field value, lastName. If the target field does not exist, it is created.

[
  {
     "operation":"move",
     "from":"surname",
     "field":"lastName"
  }
]

To apply a move operation on an array, you need a compatible single-value, list semantic array, or set semantic array on both the source and the target. For details, see the criteria described in "Patch Operation: Add".

A.2.10.5. Patch Operation: Remove

The remove operation ensures that the target field no longer contains the value provided. If the remove operation does not include a value, the operation removes the field. The following remove deletes the value of the phoneNumber, along with the field.

[
  {
    "operation" : "remove",
    "field" : "phoneNumber"
  }
]

If the object has more than one phoneNumber, those values are stored as an array.

A remove operation has different results on two standard types of arrays:

  • List semantic arrays: A remove operation deletes the specified element in the array. For example, the following operation removes the first phone number, based on its array index (zero-based):

    [
       {
          "operation" : "remove",
          "field" : "/phoneNumber/0"
       }
    ]
  • Set semantic arrays: The list of values included in a patch are removed from the existing array.

A.2.10.6. Patch Operation: Replace

The replace operation removes any existing value(s) of the targeted field, and replaces them with the provided value(s). It is essentially equivalent to a remove followed by a add operation. If the arrays are used, the criteria is based on "Patch Operation: Add". However, indexed updates are not allowed, even when the target is an array.

The following replace operation removes the existing telephoneNumber value for the user, and then adds the new value of +1 408 555 9999.

[
  {
    "operation" : "replace",
    "field" : "/telephoneNumber",
    "value" : "+1 408 555 9999"
  }
]

A PATCH replace operation on a list semantic array works in the same fashion as a PATCH remove operation. The following example demonstrates how the effect of both operations. Start with the following resource:

{
    "fruits" : [ "apple", "orange", "kiwi", "lime" ],
}

Apply the following operations on that resource:

[
  {
    "operation" : "remove",
    "field" : "/fruits/0",
    "value" : ""
  },
  {
    "operation" : "replace",
    "field" : "/fruits/1",
    "value" : "pineapple"
  }
]

The PATCH operations are applied sequentially. The remove operation removes the first member of that resource, based on its array index, (fruits/0), with the following result:

[
  {
    "fruits" : [ "orange", "kiwi", "lime" ],
  }
]

The second PATCH operation, a replace, is applied on the second member (fruits/1) of the intermediate resource, with the following result:

[
  {
    "fruits" : [ "orange", "pineapple", "lime" ],
  }
]

A.2.10.7. Patch Operation: Transform

The transform operation changes the value of a field based on a script or some other data transformation command. The following transform operation takes the value from the field named /objects, and applies the something.js script as shown:

[
  {
    "operation" : "transform",
    "field" : "/objects",
    "value" : {
      "script" : {
        "type" : "text/javascript",
        "file" : "something.js"
      }
    }
  }
]

A.2.10.8. Patch Operation Limitations

Some HTTP client libraries do not support the HTTP PATCH operation. Make sure that the library you use supports HTTP PATCH before using this REST operation.

For example, the Java Development Kit HTTP client does not support PATCH as a valid HTTP method. Instead, the method HttpURLConnection.setRequestMethod("PATCH") throws ProtocolException.

Parameters

You can use the following parameters. Other parameters might depend on the specific action implementation:

_prettyPrint=true

Format the body of the response.

_fields=field[,field...]

Return only the specified fields in the body of the response.

The field values are JSON pointers. For example if the resource is {"parent":{"child":"value"}}, parent/child refers to the "child":"value".

A.2.11. Action

Actions are a means of extending Common REST APIs and are defined by the resource provider, so the actions you can use depend on the implementation.

The standard action indicated by _action=create is described in "Create".

Parameters

You can use the following parameters. Other parameters might depend on the specific action implementation:

_prettyPrint=true

Format the body of the response.

_fields=field[,field...]

Return only the specified fields in the body of the response.

The field values are JSON pointers. For example if the resource is {"parent":{"child":"value"}}, parent/child refers to the "child":"value".

A.2.12. Query

To query a resource collection (or resource container if you prefer to think of it that way), perform an HTTP GET and accept a JSON response, including at least a _queryExpression, _queryFilter, or _queryId parameter. These parameters cannot be used together:

GET /users?_queryFilter=true HTTP/1.1
Host: example.com
Accept: application/json
  

The server returns the result as a JSON object including a "results" array and other fields related to the query string parameters that you specify.

Parameters

You can use the following parameters:

_queryFilter=filter-expression

Query filters request that the server return entries that match the filter expression. You must URL-escape the filter expression.

The string representation is summarized as follows. Continue reading for additional explanation:

Expr           = OrExpr
OrExpr         = AndExpr ( 'or' AndExpr ) *
AndExpr        = NotExpr ( 'and' NotExpr ) *
NotExpr        = '!' PrimaryExpr | PrimaryExpr
PrimaryExpr    = '(' Expr ')' | ComparisonExpr | PresenceExpr | LiteralExpr
ComparisonExpr = Pointer OpName JsonValue
PresenceExpr   = Pointer 'pr'
LiteralExpr    = 'true' | 'false'
Pointer        = JSON pointer
OpName         = 'eq' |  # equal to
                 'co' |  # contains
                 'sw' |  # starts with
                 'lt' |  # less than
                 'le' |  # less than or equal to
                 'gt' |  # greater than
                 'ge' |  # greater than or equal to
                 STRING  # extended operator
JsonValue      = NUMBER | BOOLEAN | '"' UTF8STRING '"'
STRING         = ASCII string not containing white-space
UTF8STRING     = UTF-8 string possibly containing white-space
     

JsonValue components of filter expressions follow RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format. In particular, as described in section 7 of the RFC, the escape character in strings is the backslash character. For example, to match the identifier test\, use _id eq 'test\\'. In the JSON resource, the \ is escaped the same way: "_id":"test\\".

When using a query filter in a URL, be aware that the filter expression is part of a query string parameter. A query string parameter must be URL encoded as described in RFC 3986: Uniform Resource Identifier (URI): Generic Syntax For example, white space, double quotes ("), parentheses, and exclamation characters need URL encoding in HTTP query strings. The following rules apply to URL query components:

query       = *( pchar / "/" / "?" )
pchar       = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
                  / "*" / "+" / "," / ";" / "="
     

ALPHA, DIGIT, and HEXDIG are core rules of RFC 5234: Augmented BNF for Syntax Specifications:

ALPHA       =  %x41-5A / %x61-7A   ; A-Z / a-z
DIGIT       =  %x30-39             ; 0-9
HEXDIG      =  DIGIT / "A" / "B" / "C" / "D" / "E" / "F"
     

As a result, a backslash escape character in a JsonValue component is percent-encoded in the URL query string parameter as %5C. To encode the query filter expression _id eq 'test\\', use _id+eq+'test%5C%5C', for example.

A simple filter expression can represent a comparison, presence, or a literal value.

For comparison expressions use json-pointer comparator json-value, where the comparator is one of the following:

eq (equals)
co (contains)
sw (starts with)
lt (less than)
le (less than or equal to)
gt (greater than)
ge (greater than or equal to)

For presence, use json-pointer pr to match resources where the JSON pointer is present.

Literal values include true (match anything) and false (match nothing).

Complex expressions employ and, or, and ! (not), with parentheses, (expression), to group expressions.

_queryId=identifier

Specify a query by its identifier.

Specific queries can take their own query string parameter arguments, which depend on the implementation.

_pagedResultsCookie=string

The string is an opaque cookie used by the server to keep track of the position in the search results. The server returns the cookie in the JSON response as the value of pagedResultsCookie.

In the request _pageSize must also be set and non-zero. You receive the cookie value from the provider on the first request, and then supply the cookie value in subsequent requests until the server returns a null cookie, meaning that the final page of results has been returned.

The _pagedResultsCookie parameter is supported when used with the _queryFilter parameter. The _pagedResultsCookie parameter is not guaranteed to work when used with the _queryExpression and _queryId parameters.

The _pagedResultsCookie and _pagedResultsOffset parameters are mutually exclusive, and not to be used together.

_pagedResultsOffset=integer

When _pageSize is non-zero, use this as an index in the result set indicating the first page to return.

The _pagedResultsCookie and _pagedResultsOffset parameters are mutually exclusive, and not to be used together.

_pageSize=integer

Return query results in pages of this size. After the initial request, use _pagedResultsCookie or _pageResultsOffset to page through the results.

_totalPagedResultsPolicy=string

When a _pageSize is specified, and non-zero, the server calculates the "totalPagedResults", in accordance with the totalPagedResultsPolicy, and provides the value as part of the response. The "totalPagedResults" is either an estimate of the total number of paged results (_totalPagedResultsPolicy=ESTIMATE), or the exact total result count (_totalPagedResultsPolicy=EXACT). If no count policy is specified in the query, or if _totalPagedResultsPolicy=NONE, result counting is disabled, and the server returns value of -1 for "totalPagedResults".

_sortKeys=[+-]field[,[+-]field...]

Sort the resources returned based on the specified field(s), either in + (ascending, default) order, or in - (descending) order.

The _sortKeys parameter is not supported for predefined queries (_queryId).

_prettyPrint=true

Format the body of the response.

_fields=field[,field...]

Return only the specified fields in each element of the "results" array in the response.

The field values are JSON pointers. For example if the resource is {"parent":{"child":"value"}}, parent/child refers to the "child":"value".

A.2.13. HTTP Status Codes

When working with a Common REST API over HTTP, client applications should expect at least the following HTTP status codes. Not all servers necessarily return all status codes identified here:

200 OK

The request was successful and a resource returned, depending on the request.

201 Created

The request succeeded and the resource was created.

204 No Content

The action request succeeded, and there was no content to return.

304 Not Modified

The read request included an If-None-Match header, and the value of the header matched the revision value of the resource.

400 Bad Request

The request was malformed.

401 Unauthorized

The request requires user authentication.

403 Forbidden

Access was forbidden during an operation on a resource.

404 Not Found

The specified resource could not be found, perhaps because it does not exist.

405 Method Not Allowed

The HTTP method is not allowed for the requested resource.

406 Not Acceptable

The request contains parameters that are not acceptable, such as a resource or protocol version that is not available.

409 Conflict

The request would have resulted in a conflict with the current state of the resource.

410 Gone

The requested resource is no longer available, and will not become available again. This can happen when resources expire for example.

412 Precondition Failed

The resource's current version does not match the version provided.

415 Unsupported Media Type

The request is in a format not supported by the requested resource for the requested method.

428 Precondition Required

The resource requires a version, but no version was supplied in the request.

500 Internal Server Error

The server encountered an unexpected condition that prevented it from fulfilling the request.

501 Not Implemented

The resource does not support the functionality required to fulfill the request.

503 Service Unavailable

The requested resource was temporarily unavailable. The service may have been disabled, for example.

A.3. REST API Versioning

In OpenAM 12.0.0 and later, REST API features are assigned version numbers.

Providing version numbers in the REST API helps ensure compatibility between OpenAM releases. The version number of a feature increases when OpenAM introduces a non-backwards-compatible change that affects clients making use of the feature.

OpenAM provides versions for the following aspects of the REST API.

resource

Any changes to the structure or syntax of a returned response will incur a resource version change. For example changing errorMessage to message in a JSON response.

protocol

Any changes to the methods used to make REST API calls will incur a protocol version change. For example changing _action to $action in the required parameters of an API feature.

A.3.1. Supported REST API Versions

The REST API version numbers supported in AM 5.0.0 are as follows:

Supported protocol versions

The protocol versions supported in AM 5.0.0 are:

1.0
Supported resource versions

The resource versions supported in AM 5.0.0 are shown in the following table.

Supported resource Versions
BaseEnd PointSupported Versions
/json/authenticate1.1, 2.0
/users1.1, 1.2, 2.0, 2.1, 3.0
/groups1.1, 2.0, 2.1, 3.0
/agents1.1, 2.0, 2.1, 3.0
/realms1.0
/dashboard1.0
/sessions1.1
/serverinfo/*1.1
/users/{user}/devices/trusted1.0
/users/{user}/uma/policies1.0
/applications1.0, 2.0
/resourcetypes1.0
/policies1.0, 2.0
/applicationtypes1.0
/conditiontypes1.0
/subjecttypes1.0
/subjectattributes1.0
/decisioncombiners1.0
/subjectattributes1.0
/xacml/policies1.0
/frrest/token1.0
/client1.0

The OpenAM Release Notes section, "Changes and Deprecated Functionality" in the Release Notes describes the differences between API versions.

A.3.2. Specifying an Explicit REST API Version

You can specify which version of the REST API to use by adding an Accept-API-Version header to the request, as in the following example, which is requesting resource version 2.0 and protocol version 1.0:

$ curl \
 --request POST \
 --header "X-OpenAM-Username: demo" \
 --header "X-OpenAM-Password: changeit" \
 --header "Accept-API-Version: resource=2.0, protocol=1.0" \
 https://openam.example.com:8443/openam/json/realms/root/authenticate

You can configure the default behavior OpenAM will take when a REST call does not specify explicit version information. For more information, see "Configuring the Default REST API Version for a Deployment".

A.3.3. Configuring the Default REST API Version for a Deployment

You can configure the default behavior OpenAM will take when a REST call does not specify explicit version information using either of the following procedures:

The available options for default behavior are as follows:

Latest

The latest available supported version of the API is used.

This is the preset default for new installations of OpenAM.

Oldest

The oldest available supported version of the API is used.

This is the preset default for upgraded OpenAM instances.

Note

The oldest supported version may not be the first that was released, as APIs versions become deprecated or unsupported. See "Deprecated Functionality" in the Release Notes.

None

No version will be used. When a REST client application calls a REST API without specifying the version, OpenAM returns an error and the request fails.

Configure Versioning Behavior by using the AM Console
  1. Log in as OpenAM administrator, amadmin.

  2. Click Configure > Global Services, and then click REST APIs.

  3. In Default Version, select the required response to a REST API request that does not specify an explicit version: Latest, Oldest, or None.

  4. (Optional) Optionally, enable Warning Header to include warning messages in the headers of responses to requests.

  5. Save your work.

Configure Versioning Behavior by using the ssoadm
  • Use the ssoadm set-attr-defs command with the openam-rest-apis-default-version attribute set to either LATEST, OLDEST or NONE, as in the following example:

    $ ssh openam.example.com
    $ cd /path/to/openam-tools/admin/openam/bin
    $ ./ssoadm \
     set-attr-defs \
     --adminid amadmin \
     --password-file /tmp/pwd.txt \
     --servicename RestApisService \
     --schematype Global \
     --attributevalues openam-rest-apis-default-version=NONE
    
    Schema attribute defaults were set.

A.3.4. REST API Versioning Messages

OpenAM provides REST API version messages in the JSON response to a REST API call. You can also configure OpenAM to return version messages in the response headers.

Messages include:

  • Details of the REST API versions used to service a REST API call.

  • Warning messages if REST API version information is not specified or is incorrect in a REST API call.

The resource and protocol version used to service a REST API call are returned in the Content-API-Version header, as shown below:

$ curl \
 -i \
 --request POST \
 --header "X-OpenAM-Username: demo" \
 --header "X-OpenAM-Password: changeit" \
 --header "Accept-API-Version: resource=2.0, protocol=1.0" \
 https://openam.example.com:8443/openam/json/realms/root/authenticate

HTTP/1.1 200 OK
Content-API-Version: protocol=1.0,resource=2.0
Server: Restlet-Framework/2.1.7
Content-Type: application/json;charset=UTF-8

{
 "tokenId":"AQIC5wM...TU3OQ*",
 "successUrl":"/openam/console"
}

If the default REST API version behavior is set to None, and a REST API call does not include the Accept-API-Version header, or does not specify a resource version, then a 400 Bad Request status code is returned, as shown below:

$ curl \
 --header "Content-Type: application/json" \
 --header "Accept-API-Version: protocol=1.0" \
 https://openam.example.com:8443/openam/json/realms/root/serverinfo/*

{
 "code":400,
 "reason":"Bad Request",
 "message":"No requested version specified and behavior set to NONE."
}

If a REST API call does include the Accept-API-Version header, but the specified resource or protocol version does not exist in OpenAM, then a 404 Not Found status code is returned, as shown below:

$ curl \
 --header "Content-Type: application/json" \
 --header "Accept-API-Version: protocol=1.0, resource=999.0" \
 https://openam.example.com:8443/openam/json/realms/root/serverinfo/*

{
 "code":404,
 "reason":"Not Found",
 "message":"Accept-API-Version: Requested version \"999.0\" does not match any routes."
}

Tip

For more information on setting the default REST API version behavior, see "Specifying an Explicit REST API Version".

A.4. Specifying Realms in REST API Calls

This section describes how to work with realms when making REST API calls to OpenAM.

Realms can be specified in the following ways when making a REST API call to OpenAM:

DNS Alias

When making a REST API call, the DNS alias of a realm can be specified in the subdomain and domain name components of the REST endpoint.

To list all users in the top-level realm use the DNS alias of the OpenAM instance, for example the REST endpoint would be:

https://openam.example.com:8443/openam/json/users?_queryId=*

To list all users in a realm with DNS alias suppliers.example.com the REST endpoint would be:

https://suppliers.example.com:8443/openam/json/users?_queryId=*

Path

When making a REST API call, specify the realm in the path component of the endpoint. You must specify the entire hierarchy of the realm, starting at the top-level realm. Prefix each realm in the hierarchy with the realms/ keyword. For example /realms/root/realms/customers/realms/europe.

To authenticate a user in the top-level realm, use the root keyword. For example:

https://openam.example.com:8443/openam/json/realms/root/authenticate

To authenticate a user in a subrealm named customers within the top-level realm, the REST endpoint would be:

https://openam.example.com:8443/openam/json/realms/root/realms/customers/authenticate

If realms are specified using both the DNS alias and path methods, the path is used to determine the realm.

For example, the following REST endpoint returns users in a subrealm of the top-level realm named europe, not the realm with DNS alias suppliers.example.com:

https://suppliers.example.com:8443/openam/json/realms/root/realms/europe/users?_queryId=*

A.5. Authentication and Logout

You can use REST-like APIs under /json/authenticate and /json/sessions for authentication and for logout.

The /json/authenticate endpoint does not support the CRUDPAQ verbs and therefore does not technically satisfy REST architectural requirements. The term REST-like describes this endpoint better than REST.

The simplest user name/password authentication returns a tokenId that applications can present as a cookie value for other operations that require authentication. The type of tokenId returned varies depending on whether stateless sessions are enabled in the realm to which the user authenticates:

  • If stateless sessions are not enabled, the tokenId is an OpenAM SSO token.

  • If stateless sessions are enabled, the tokenId is an OpenAM SSO token that includes an encoded OpenAM session.

Developers should be aware that the size of the tokenId for stateless sessions—2000 bytes or greater—is considerably longer than for stateful sessions—approximately 100 bytes. For more information about stateful and stateless session tokens, see "Session Cookies" in the Authentication and Single Sign-On Guide.

When authenticating with a user name and password, use HTTP POST to prevent the web container from logging the credentials. Pass the user name in an X-OpenAM-Username header, and the password in an X-OpenAM-Password header:

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "X-OpenAM-Username: demo" \
 --header "X-OpenAM-Password: changeit" \
 --header "Accept-API-Version: resource=2.0, protocol=1.0" \
 --data "{}" \
 https://openam.example.com:8443/openam/json/realms/root/authenticate
{
 "tokenId": "AQIC5w...NTcy*",
 "successUrl": "/openam/console",
 "realm":"/"
}

To use UTF-8 user names and passwords in calls to the /json/authenticate endpoint, base64-encode the string, and then wrap the string as described in RFC 2047:

encoded-word = "=?" charset "?" encoding "?" encoded-text "?="

For example, to authenticate using a UTF-8 username, such as ɗëɱø, perform the following steps:

  1. Encode the string in base64 format: yZfDq8mxw7g=.

  2. Wrap the base64-encoded string as per RFC 2047: =?UTF-8?B?yZfDq8mxw7g=?=.

  3. Use the result in the X-OpenAM-Username header passed to the authentication endpoint as follows:

    $ curl \
     --request POST \
     --header "Content-Type: application/json" \
     --header "X-OpenAM-Username: =?UTF-8?B?yZfDq8mxw7g=?=" \
     --header "X-OpenAM-Password: changeit" \
     --header "Accept-API-Version: resource=2.0, protocol=1.0" \
     --data "{}" \
     https://openam.example.com:8443/openam/json/realms/root/authenticate
    {
     "tokenId": "AQIC5w...NTcy*",
     "successUrl": "/openam/console",
     "realm":"/"
    }

This zero page login mechanism works only for name/password authentication. If you include a POST body with the request, it must be an empty JSON string as shown in the example. Alternatively, you can leave the POST body empty. Otherwise, OpenAM interprets the body as a continuation of an existing authentication attempt, one that uses a supported callback mechanism.

The authentication service at /json/authenticate supports callback mechanisms that make it possible to perform other types of authentication in addition to simple user name/password login.

Callbacks that are not completed based on the content of the client HTTP request are returned in JSON as a response to the request. Each callback has an array of output suitable for displaying to the end user, and input which is what the client must complete and send back to OpenAM. The default is still user name/password authentication:

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "Accept-API-Version: resource=2.0, protocol=1.0" \
 https://openam.example.com:8443/openam/json/realms/root/authenticate
{
    "authId": "...jwt-value...",
    "template": "",
    "stage": "DataStore1",
    "callbacks": [
        {
            "type": "NameCallback",
            "output": [
                {
                    "name": "prompt",
                    "value": " User Name: "
                }
            ],
            "input": [
                {
                    "name": "IDToken1",
                    "value": ""
                }
            ]
        },
        {
            "type": "PasswordCallback",
            "output": [
                {
                    "name": "prompt",
                    "value": " Password: "
                }
            ],
            "input": [
                {
                    "name": "IDToken2",
                    "value": ""
                }
            ]
        }
    ]
}

The authID value is a JSON Web Token (JWT) that uniquely identifies the authentication context to OpenAM, and so must also be sent back with the requests.

To respond to the callback, send back the JSON object with the missing values filled, as in this case where the user name is demo and the password is changeit:

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "Accept-API-Version: resource=2.0, protocol=1.0" \
 --data '{ "authId": "...jwt-value...", "template": "", "stage": "DataStore1",
   "callbacks": [ { "type": "NameCallback", "output": [ { "name": "prompt",
   "value": " User Name: " } ], "input": [ { "name": "IDToken1", "value": "demo" } ] },
   { "type": "PasswordCallback", "output": [ { "name": "prompt", "value": " Password: " } ],
   "input": [ { "name": "IDToken2", "value": "changeit" } ] } ] }' \
 https://openam.example.com:8443/openam/json/realms/root/authenticate

{ "tokenId": "AQIC5wM2...U3MTE4NA..*", "successUrl": "/openam/console", "realm":"/" }

The response is a token ID holding the SSO token value.

Alternatively, you can authenticate without requesting a session using the noSession query string parameter:

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "Accept-API-Version: resource=2.0, protocol=1.0" \
 --data '{ "authId": "...jwt-value...", "template": "", "stage": "DataStore1",
   "callbacks": [ { "type": "NameCallback", "output": [ { "name": "prompt",
   "value": " User Name: " } ], "input": [ { "name": "IDToken1", "value": "demo" } ] },
   { "type": "PasswordCallback", "output": [ { "name": "prompt", "value": " Password: " } ],
   "input": [ { "name": "IDToken2", "value": "changeit" } ] } ] }' \
 https://openam.example.com:8443/openam/json/realms/root/authenticate?noSession=true

{ "message": "Authentication Successful", "successUrl": "/openam/console", "realm":"/" }

OpenAM can be configured to return a failure URL value when authentication fails. No failure URL is configured by default. The Default Failure Login URL can be set per realm; see "Post Authentication Processing" in the Authentication and Single Sign-On Guide for details. Alternatively, failure URLs can be configured per authentication chain, which your client can specify using the service parameter described below. On failure OpenAM then returns HTTP status code 401 Unauthorized, and the JSON in the reply indicates the failure URL:

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "X-OpenAM-Username: demo" \
 --header "X-OpenAM-Password: badpassword" \
 --header "Accept-API-Version: resource=2.0, protocol=1.0" \
 https://openam.example.com:8443/openam/json/realms/root/authenticate
{
  "code":401,
  "reason":"Unauthorized",
  "message":"Invalid Password!!",
  "failureUrl": "http://www.example.com/401.html"
}

When making a REST API call, specify the realm in the path component of the endpoint. You must specify the entire hierarchy of the realm, starting at the top-level realm. Prefix each realm in the hierarchy with the realms/ keyword. For example /realms/root/realms/customers/realms/europe.

For example, to authenticate to a subrealm customers within the top-level realm, then the authentication endpoint URL is as follows: https://openam.example.com:8443/openam/json/realms/root/realms/customers/authenticate

The following additional parameters are supported:

You can use the authIndexType and authIndexValue query string parameters as a pair to provide additional information about how you are authenticating. The authIndexType can be one of the following types:

composite

Set the value to a composite advice string.

level

Set the value to the authentication level.

module

Set the value to the name of an authentication module.

resource

Set the value to a URL protected by an OpenAM policy.

role

Set the value to an OpenAM role.

service

Set the value to the name of an authentication chain.

user

Set the value to an OpenAM user ID.

For example, to log into AM using the built-in ldapService authentication chain, you could use the following:

$ curl \
--request POST \
--header 'Accept-API-Version: resource=2.0, protocol=1.0' \
--header 'X-OpenAM-Username: demo' \
--header 'X-OpenAM-Password: changeit' \
'http://openam.example.com:8080/openam/json/authenticate?authIndexType=service&authIndexValue=ldapService'

You can use the query string parameter, sessionUpgradeSSOTokenId=tokenId, to request session upgrade. Before the tokenId is searched for in the query string for session upgrade, the token is grabbed from the cookie. For an explanation of session upgrade, see "Session Upgrade" in the Authentication and Single Sign-On Guide.

OpenAM uses the following callback types depending on the authentication module in use:

  • ChoiceCallback: Used to display a list of choices and retrieve the selected choice.

  • ConfirmationCallback: Used to ask for a confirmation such as Yes, No, or Cancel and retrieve the selection.

  • HiddenValueCallback: Used to return form values that are not visually rendered to the end user.

  • HttpCallback: Used for HTTP handshake negotiations.

  • LanguageCallback: Used to retrieve the locale for localizing text presented to the end user.

  • NameCallback: Used to retrieve a name string.

  • PasswordCallback: Used to retrieve a password value.

  • RedirectCallback: Used to redirect the client user-agent.

  • ScriptTextOutputCallback: Used to insert a script into the page presented to the end user. The script can, for example, collect data about the user's environment.

  • TextInputCallback: Used to retrieve text input from the end user.

  • TextOutputCallback: Used to display a message to the end user.

  • X509CertificateCallback: Used to retrieve the content of an x.509 certificate.

A.5.1. Logout

Authenticated users can log out with the token cookie value and an HTTP POST to /json/sessions/?_action=logout:

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "Cache-Control: no-cache" \
 --header "iplanetDirectoryPro: AQIC5wM2...U3MTE4NA..*" \
 --header "Accept-API-Version: resource=1.1, protocol=1.0" \
 https://openam.example.com:8443/openam/json/realms/root/sessions/?_action=logout
   
    {"result":"Successfully logged out"}

A.5.2. logoutByHandle

To log out a session using a session handle, first perform an HTTP GET to the resource URL, /json/sessions/, using the queryFilter action to get the session handle:

$ curl \
 --request GET \
 --header "Content-Type: application/json" \
 --header "Cache-Control: no-cache" \
 --header "iPlanetDirectoryPro: AQICS...NzEz*" \
 --header "Accept-API-Version: resource=1.1, protocol=1.0" \
 http://openam.example.com:8080/openam/json/realms/root/sessions?_queryFilter=username%20eq%20%22demo%22%20and%20realm%20eq%20%22%2F%22
{
  "result": [
   {
    "username": "demo",
    "universalId": "id=demo,ou=user,dc=openam,dc=forgerock,dc=org",
    "realm": "\/",
    "sessionHandle": "shandle:AQIC5w...MTY3*",
    "latestAccessTime": "2016-11-09T14:14:11Z",
    "maxIdleExpirationTime": "2016-11-09T14:44:11Z",
    "maxSessionExpirationTime": "2016-11-09T16:14:11Z"
   }
  ],
   "resultCount": 1,
   "pagedResultsCookie": null,
   "totalPagedResultsPolicy": "NONE",
   "totalPagedResults": -1,
   "remainingPagedResults": -1
}

To log out a session using a session handle, perform an HTTP POST to the resource URL, /json/sessions/, using the logoutByHandle action.

$ curl \
 --request POST \
 --header "Content-Type: application/json" \
 --header "Cache-Control: no-cache" \
 --header "iplanetDirectoryPro: AQIC5w...NTcy*" \
 --header "Accept-API-Version: resource=1.1, protocol=1.0" \
 --data '{"sessionHandles": ["shandle:AQIC5w...MTY3*","shandle:AQIC5w...NDcx*"]}' \
http://openam.example.com:8080/openam/json/realms/root/sessions/?_action=logoutByHandle
{
  "result": {
    "shandle:AQIC5w...NDcx*": true,
    "shandle:AQIC5w...MTY3*": true
  }
}

A.5.3. Load Balancer and Proxy Layer Requirements

When authentication depends on the client IP address and OpenAM lies behind a load balancer or proxy layer, configure the load balancer or proxy to send the address by using the X-Forwarded-For header, and configure OpenAM to consume and forward the header as necessary. For details, see "Handling HTTP Request Headers" in the Installation Guide.

A.5.4. Windows Desktop SSO Requirements

When authenticating with Windows Desktop SSO, add an Authorization header containing the string Basic , followed by a base64-encoded string of the username, a colon character, and the password. In the following example, the credentials demo:changeit are base64-encoded into the string ZGVtbzpjaGFuZ2VpdA==:

$ curl \
--request POST \
--header "Content-Type: application/json" \
--header "X-OpenAM-Username: demo" \
--header "X-OpenAM-Password: changeit" \
--header "Authorization: Basic ZGVtbzpjaGFuZ2VpdA==" \
--header "Accept-API-Version: resource=2.0, protocol=1.0" \
--data "{}" \
https://openam.example.com:8443/openam/json/realms/root/authenticate

{ "tokenId": "AQIC5w...NTcy*", "successUrl": "/openam/console", "realm":"/" }

A.6. Using the Session Token After Authentication

The following is a common scenario when accessing OpenAM by using REST API calls:

  • First, call the /json/authenticate endpoint to log a user in to OpenAM. This REST API call returns a tokenID value, which is used in subsequent REST API calls to identify the user:

    $ curl \
     --request POST \
     --header "Content-Type: application/json" \
     --header "X-OpenAM-Username: demo" \
     --header "X-OpenAM-Password: changeit" \
     --header "Accept-API-Version: resource=2.0, protocol=1.0" \
     --data "{}" \
     https://openam.example.com:8443/openam/json/realms/root/authenticate
    
    { "tokenId": "AQIC5w...NTcy*", "successUrl": "/openam/console" }

    The returned tokenID is known as a session token (also referred to as an SSO token). REST API calls made after successful authentication to OpenAM must present the session token in the HTTP header as proof of authentication.

  • Next, call one or more additional REST APIs on behalf of the logged-in user. Each REST API call passes the user's tokenID back to OpenAM in the HTTP header as proof of previous authentication.

    The following is a partial example of a curl command that inserts the token ID returned from a prior successful OpenAM authentication attempt into the HTTP header:

    $ curl \
    --request POST \
    --header "Content-Type: application/json" \
    --header "iPlanetDirectoryPro: AQIC5w...NTcy*" \
    --header "Accept-API-Version: resource=2.0, protocol=1.0" \
    --data '{
      ...
    

    Observe that the session token is inserted into a header field named iPlanetDirectoryPro. This header field name must correspond to the name of the OpenAM session cookie—by default, iPlanetDirectoryPro. You can find the cookie name in the AM console by navigating to Deployment > Servers > Server Name > Security > Cookie, in the Cookie Name field of the AM console.

    Once a user has authenticated, it is not necessary to insert login credentials in the HTTP header in subsequent REST API calls. Note the absence of X-OpenAM-Username and X-OpenAM-Password headers in the preceding example.

    Users are required to have appropriate privileges in order to access OpenAM functionality using the REST API. For example, users who lack administrative privileges cannot create OpenAM realms. For more information on the OpenAM privilege model, see "Delegating Realm Administration Privileges" in the Setup and Maintenance Guide.

  • Finally, call the REST API to log the user out of OpenAM as described in "Authentication and Logout". As with other REST API calls made after a user has authenticated, the REST API call to log out of OpenAM requires the user's tokenID in the HTTP header.

A.7. Server Information

You can retrieve OpenAM server information by using HTTP GET on /json/serverinfo/* as follows:

$ curl \
 --request GET \
 --header "Content-Type: application/json" \
 --header "Accept-API-Version: resource=1.1, protocol=1.0" \
 https://openam.example.com:8443/openam/json/serverinfo/*
{
    "domains": [
        ".example.com"
    ],
    "protectedUserAttributes": [],
    "cookieName": "iPlanetDirectoryPro",
    "secureCookie": false,
    "forgotPassword": "false",
    "forgotUsername": "false",
    "kbaEnabled": "false",
    "selfRegistration": "false",
    "lang": "en-US",
    "successfulUserRegistrationDestination": "default",
    "socialImplementations": [
        {
            "iconPath": "XUI/images/logos/facebook.png",
            "authnChain": "FacebookSocialAuthenticationService",
            "displayName": "Facebook",
            "valid": true
        }
    ],
    "referralsEnabled": "false",
    "zeroPageLogin": {
        "enabled": false,
        "refererWhitelist": [
            ""
        ],
        "allowedWithoutReferer": true
    },
    "realm": "/",
    "xuiUserSessionValidationEnabled": true,
    "FQDN": "openam.example.com"
}

A.8. Token Encoding

Valid tokens in OpenAM requires configuration either in percent encoding or in C66Encode format. C66Encode format is encouraged. It is the default token format for OpenAM, and is used in this section. The following is an example token that has not been encoded:

AQIC5wM2LY4SfczntBbXvEAOuECbqMY3J4NW3byH6xwgkGE=@AAJTSQACMDE=#

This token includes reserved characters such as +, /, and = (The @, #, and * are not reserved characters per se, but substitutions are still required). To c66encode this token, you would substitute certain characters for others, as follows:

+ is replaced with -
/ is replaced with _
= is replaced with .
@ is replaced with *
# is replaced with *
* (first instance) is replaced with @
* (subsequent instances) is replaced with #

In this case, the translated token would appear as shown here:

AQIC5wM2LY4SfczntBbXvEAOuECbqMY3J4NW3byH6xwgkGE.*AAJTSQACMDE.*

A.9. Logging

AM 5.0.0 supports two Audit Logging Services: a new common REST-based Audit Logging Service, and the legacy Logging Service, which is based on a Java SDK and is available in OpenAM versions prior to OpenAM 13. The legacy Logging Service is deprecated.

Both audit facilities log OpenAM REST API calls.

A.9.1. Common Audit Logging of REST API Calls

OpenAM logs information about all REST API calls to the access topic. For more information about OpenAM audit topics, see "Audit Log Topics" in the Setup and Maintenance Guide.

Locate specific REST endpoints in the http.path log file property.

A.9.2. Legacy Logging of REST API Calls

OpenAM logs information about REST API calls to two files:

  • amRest.access. Records accesses to a CREST endpoint, regardless of whether the request successfully reached the endpoint through policy authorization.

    An amRest.access example is as follows:

    $ cat openam/openam/log/amRest.access
    
    #Version: 1.0
    #Fields: time  Data  LoginID  ContextID  IPAddr  LogLevel  Domain  LoggedBy  MessageID  ModuleName
    NameID  HostName
    "2011-09-14 16:38:17"   /home/user/openam/openam/log/ "cn=dsameuser,ou=DSAME Users,o=openam"
    aa307b2dcb721d4201 "Not Available" INFO  o=openam   "cn=dsameuser,ou=DSAME Users,o=openam"
    LOG-1  amRest.access  "Not Available"  192.168.56.2
    "2011-09-14 16:38:17"  "Hello World"  id=bjensen,ou=user,o=openam 8a4025a2b3af291d01  "Not Available"
    INFO  o=openam id=amadmin,ou=user,o=openam "Not Available" amRest.access "Not Available"
    192.168.56.2
  • amRest.authz. Records all CREST authorization results regardless of success. If a request has an entry in the amRest.access log, but no corresponding entry in amRest.authz, then that endpoint was not protected by an authorization filter and therefore the request was granted access to the resource.

    The amRest.authz file contains the Data field, which specifies the authorization decision, resource, and type of action performed on that resource. The Data field has the following syntax:

    ("GRANT"||"DENY") > "RESOURCE | ACTION"
    
    where
      "GRANT > " is prepended to the entry if the request was allowed
      "DENY  > " is prepended to the entry if the request was not allowed
      "RESOURCE" is "ResourceLocation | ResourceParameter"
         where
           "ResourceLocation" is the endpoint location (e.g., subrealm/applicationtypes)
           "ResourceParameter" is the ID of the resource being touched
            (e.g., myApplicationType) if applicable. Otherwise, this field is empty
            if touching the resource itself, such as in a query.
    
      "ACTION" is "ActionType | ActionParameter"
         where
           "ActionType" is "CREATE||READ||UPDATE||DELETE||PATCH||ACTION||QUERY"
           "ActionParameter" is one of the following depending on the ActionType:
              For CREATE: the new resource ID
              For READ: empty
              For UPDATE: the revision of the resource to update
              For DELETE: the revision of the resource to delete
              For PATCH: the revision of the resource to patch
              For ACTION: the actual action performed (e.g., "forgotPassword")
              For QUERY: the query ID if any
    $ cat openam/openam/log/amRest.authz
    
    #Version: 1.0
    #Fields: time   Data  ContextID  LoginID  IPAddr  LogLevel  Domain  MessageID  LoggedBy  NameID
    ModuleName    HostName
    "2014-09-16 14:17:28"   /var/root/openam/openam/log/   7d3af9e799b6393301
    "cn=dsameuser,ou=DSAME Users,dc=openam,dc=forgerock,dc=org" "Not Available" INFO
    dc=openam,dc=forgerock,dc=org  LOG-1  "cn=dsameuser,ou=DSAME Users,dc=openam,dc=forgerock,dc=org"
    "Not Available" amRest.authz    10.0.1.5
    "2014-09-16 15:56:12"  "GRANT > sessions|ACTION|logout|AdminOnlyFilter"  d3977a55a2ee18c201
    id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org "Not Available" INFO  dc=openam,dc=forgerock,dc=org
    OAuth2Provider-2  "cn=dsameuser,ou=DSAME Users,dc=openam,dc=forgerock,dc=org"  "Not Available"
    amRest.authz    127.0.0.1
    "2014-09-16 15:56:40"   "GRANT > sessions|ACTION|logout|AdminOnlyFilter"  eedbc205bf51780001
    id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org  "Not Available" INFO dc=openam,dc=forgerock,dc=org
    OAuth2Provider-2  "cn=dsameuser,ou=DSAME Users,dc=openam,dc=forgerock,dc=org"  "Not Available"
    amRest.authz    127.0.0.1

OpenAM also provides additional information in its debug notifications for accesses to any endpoint, depending on the message type (error, warning or message) including realm, user, and result of the operation.

A.10. Reference

This reference section covers return codes and system settings relating to REST API support in AM.

A.10.1. REST APIs

amster type ID: rest

The following settings are available in this service:

Default Resource Version

The API resource version to use when the REST request does not specify an explicit version. Choose from:

  • Latest. If an explicit version is not specified, the latest resource version of an API is used.

  • Oldest. If an explicit version is not specified, the oldest supported resource version of an API is used. Note that since APIs may be deprecated and fall out of support, the oldest supported version may not be the first version.

  • None. If an explicit version is not specified, the request will not be handled and an error status is returned.

The possible values for this property are:

Latest
Oldest
None

Default value: Latest

amster data attribute: defaultVersion

Warning Header

Whether to include a warning header in the response to a request which fails to include the Accept-API-Version header.

Default value: false

amster data attribute: warningHeader

API Descriptions

Whether API Explorer and API Docs are enabled in OpenAM and how the documentation for them is generated. Dynamic generation includes descriptions from any custom services and authentication modules you may have added. Static generation only includes services and authentication modules that were present when OpenAM was built. Note that dynamic documentation generation may not work in some application containers.

The possible values for this property are:

DYNAMIC
STATIC
DISABLED

Default value: STATIC

amster data attribute: descriptionsState

Default Protocol Version

The API protocol version to use when a REST request does not specify an explicit version. Choose from:

  • Oldest. If an explicit version is not specified, the oldest protocol version is used.

  • Latest. If an explicit version is not specified, the latest protocol version is used.

  • None. If an explicit version is not specified, the request will not be handled and an error status is returned.

The possible values for this property are:

Oldest
Latest
None

Default value: Latest

amster data attribute: defaultProtocolVersion

Appendix B. About Scripting

You can use scripts for client-side and server-side authentication, policy conditions, and handling OpenID Connect claims.

B.1. The Scripting Environment

This section introduces how OpenAM executes scripts, and covers thread pools and security configuration.

You can use scripts to modify default OpenAM behavior in the following situations, also known as contexts:

Client-side Authentication

Scripts that are executed on the client during authentication. Client-side scripts must be in JavaScript.

Server-side Authentication

Scripts are included in an authentication module and are executed on the server during authentication.

Policy Condition

Scripts used as conditions within policies.

OIDC Claims

Scripts that gather and populate the claims in a request when issuing an ID token or making a request to the userinfo endpoint.

OpenAM implements a configurable scripting engine for each of the context types that are executed on the server.

The scripting engines in OpenAM have two main components: security settings, and the thread pool.

Diagram of the scripting environment within OpenAM.

B.1.1. Security

OpenAM scripting engines provide security features for ensuring that malicious Java classes are not directly called. The engines validate scripts by checking all directly-called Java classes against a configurable blacklist and whitelist, and, optionally, against the JVM SecurityManager, if it is configured.

Whitelists and blacklists contain class names that are allowed or denied execution respectively. Specify classes in whitelists and blacklists by name or by using regular expressions.

Classes called by the script are checked against the whitelist first, and must match at least one pattern in the list. The blacklist is applied after the whitelist, and classes matching any pattern are disallowed.

You can also configure the scripting engine to make an additional call to the JVM security manager for each class that is accessed. The security manager throws an exception if a class being called is not allowed to execute.

For more information on configuring script engine security, see "Scripting".

Important Points About Script Engine Security

The following points should be considered when configuring the security settings within each script engine:

The scripting engine only validates directly accessible classes.

The security settings only apply to classes that the script directly accesses. If the script calls Foo.a() and then that method calls Bar.b(), the scripting engine will be unable to prevent it. You must consider the whole chain of accessible classes.

Note

Access includes actions such as:

  • Importing or loading a class.

  • Accessing any instance of that class. For example, passed as a parameter to the script.

  • Calling a static method on that class.

  • Calling a method on an instance of that class.

  • Accessing a method or field that returns an instance of that class.

Potentially dangerous Java classes are blacklisted by default.

All Java reflection classes (java.lang.Class, java.lang.reflect.*) are blacklisted by default to avoid bypassing the security settings.

The java.security.AccessController class is also blacklisted by default to prevent access to the doPrivileged() methods.

Caution

You should not remove potentially dangerous Java classes from the blacklist.

The whitelists and blacklists match class or package names only.

The whitelist and blacklist patterns apply only to the exact class or package names involved. The script engine does not know anything about inheritance, so it is best to whitelist known, specific classes.

B.1.2. Thread Pools

Each script is executed in an individual thread. Each scripting engine starts with an initial number of threads available for executing scripts. If no threads are available for execution, OpenAM creates a new thread to execute the script, until the configured maximum number of threads is reached.

If the maximum number of threads is reached, pending script executions are queued in a number of buffer threads, until a thread becomes available for execution. If a created thread has completed script execution and has remained idle for a configured amount of time, OpenAM terminates the thread, shrinking the pool.

For more information on configuring script engine thread pools, see "Scripting".

B.2. Global Scripting API Functionality

This section covers functionality available to each of the server-side script types.

Global API functionality includes:

B.2.1. Accessing HTTP Services

OpenAM passes an HTTP client object, httpClient, to server-side scripts. Server-side scripts can call HTTP services with the httpClient.send method. The method returns an HttpClientResponse object.

Configure the parameters for the HTTP client object by using the org.forgerock.http.protocol package. This package contains the Request class, which has methods for setting the URI and type of request.

The following example, taken from the default server-side Scripted authentication module script, uses these methods to call an online API to determine the longitude and latitude of a user based on their postal address:

function getLongitudeLatitudeFromUserPostalAddress() {

    var request = new org.forgerock.http.protocol.Request();

    request.setUri("http://maps.googleapis.com/maps/api/geocode/json?address=" + encodeURIComponent(userPostalAddress));
    request.setMethod("GET");

    var response = httpClient.send(request).get();
    logResponse(response);

    var geocode = JSON.parse(response.getEntity());
    var i;

    for (i = 0; i < geocode.results.length; i++) {
        var result = geocode.results[i];
        latitude = result.geometry.location.lat;
        longitude = result.geometry.location.lng;

        logger.message("latitude:" + latitude + " longitude:" + longitude);
    }
}

HTTP client requests are synchronous and blocking until they return. You can, however, set a global timeout for server-side scripts. For details, see "Scripted Authentication Module Properties" in the Authentication and Single Sign-On Guide.

Server-side scripts can access response data by using the methods listed in the table below.

HTTP Client Response Methods
MethodParametersReturn TypeDescription

HttpClientResponse.getCookies

Void

Map<String, String>

Get the cookies for the returned response, if any exist.

HttpClientResponse.getEntity

Void

String

Get the entity of the returned response.

HttpClientResponse.getHeaders

Void

Map<String, String>

Get the headers for the returned response, if any exist.

HttpClientResponse.getReasonPhrase

Void

String

Get the reason phrase of the returned response.

HttpClientResponse.getStatusCode

Void

Integer

Get the status code of the returned response.

HttpClientResponse.hasCookies

Void

Boolean

Indicate whether the returned response had any cookies.

HttpClientResponse.hasHeaders

Void

Boolean

Indicate whether the returned response had any headers.


B.2.2. Debug Logging

Server-side scripts can write messages to OpenAM debug logs by using the logger object.

OpenAM does not log debug messages from scripts by default. You can configure OpenAM to log such messages by setting the debug log level for the amScript service. For details, see "Debug Logging By Service" in the Setup and Maintenance Guide.

The following table lists the logger methods.

Logger Methods
MethodParametersReturn TypeDescription

logger.error

Error Message (type: String)

Void

Write Error Message to OpenAM debug logs if ERROR level logging is enabled.

logger.errorEnabled

Void

Boolean

Return true when ERROR level debug messages are enabled.

logger.message

Message (type: String)

Void

Write Message to OpenAM debug logs if MESSAGE level logging is enabled.

logger.messageEnabled

Void

Boolean

Return true when MESSAGE level debug messages are enabled.

logger.warning

Warning Message (type: String)

Void

Write Warning Message to OpenAM debug logs if WARNING level logging is enabled.

logger.warningEnabled

Void

Boolean

Return true when WARNING level debug messages are enabled.


B.3. Managing Scripts

This section shows you how to manage scripts used for client-side and server-side scripted authentication, custom policy conditions, and handling OpenID Connect claims using the AM console, the ssoadm command, and the REST API.

B.3.1. Managing Scripts With the AM Console

The following procedures describe how to create, modify, and delete scripts using the AM console:

To Create Scripts by Using the AM Console
  1. Log in to the AM console as an OpenAM administrator, for example, amadmin.

  2. Navigate to Realms > Realm Name > Scripts.

  3. Click New Script.

    The New Script page appears:

    Creating a script by using the AM console.
  4. Specify a name for the script.

  5. Select the type of script from the Script Type drop-down list.

  6. Click Create.

    The Script Name page appears:

    Creating a Script Using the AM console.
  7. Enter values on the Script Name page as follows:

    1. Enter a description of the script.

    2. Choose the script language, either JavaScript or Groovy. Note that not every script type supports both languages.

    3. Enter the source code in the Script field.

      On supported browsers, you can click Upload, navigate to the script file, and then click Open to upload the contents to the Script field.

    4. Click Validate to check for compilation errors in the script.

      Correct any compilation errors, and revalidate the script until all errors have been fixed.

    5. Save your changes.

To Modify Scripts by Using the AM Console
  1. Log in to the AM console as an OpenAM administrator, for example, amadmin.

  2. Navigate to Realms > Realm Name > Scripts.

  3. Select the script you want to modify from the list of scripts.

    The Script Name page appears.

  4. Modify values on the Script Name page as needed. Note that if you change the Script Type, existing code in the script is replaced.

  5. If you modified the code in the script, click Validate to check for compilation errors.

    Correct any compilation errors, and revalidate the script until all errors have been fixed.

  6. Save your changes.

To Delete Scripts by Using the AM Console
  1. Log in to the AM console as an OpenAM administrator, for example, amadmin.

  2. Navigate to Realms > Realm Name > Scripts.

  3. Choose one or more scripts to delete by activating the checkboxes in the relevant rows. Note that you can only delete user-created scripts—you cannot delete the global sample scripts provided with OpenAM.

  4. Click Delete.

B.3.2. Managing Scripts With the ssoadm Command

Use the ssoadm command's create-sub-cfg, get-sub-cfg, and delete-sub-cfg subcommands to manage OpenAM scripts.

Create an OpenAM script as follows:

  1. Create a script configuration file as follows:

    script-file=/path/to/script-file
    language=JAVASCRIPT|GROOVY
    name=myScript
    context=AUTHENTICATION_SERVER_SIDE|AUTHENTICATION_CLIENT_SIDE|POLICY_CONDITION|OIDC_CLAIMS
  2. Run the ssoadm create-sub-cfg command. The --datafile argument references the script configuration file you created in the previous step:

    $ ssoadm \
     create-sub-cfg \
     --realm /myRealm \
     --adminid amadmin \
     --password-file /tmp/pwd.txt \
     --servicename ScriptingService \
     --subconfigname scriptConfigurations/scriptConfiguration \
     --subconfigid myScript \
     --datafile /path/to/myScriptConfigurationFile
    Sub Configuration scriptConfigurations/scriptConfiguration was added to realm /myRealm

To list the properties of a script, run the ssoadm get-sub-cfg command:

$ ssoadm \
  get-sub-cfg \
  --realm /myRealm \
  --adminid amadmin \
  --password-file /tmp/pwd.txt \
  --servicename ScriptingService \
  --subconfigname scriptConfigurations/myScript
createdBy=
lastModifiedDate=
lastModifiedBy=
name=myScript
context=POLICY_CONDITION
description=
language=JAVASCRIPT
creationDate=
script=...Script output follows...

To delete a script, run the ssoadm delete-sub-cfg command:

$ ssoadm \
  delete-sub-cfg \
  --realm /myRealm \
  --adminid amadmin \
  --password-file /tmp/pwd.txt \
  --servicename ScriptingService \
  --subconfigname scriptConfigurations/myScript
Sub Configuration scriptConfigurations/myScript was deleted from realm /myRealm

B.3.3. Managing Scripts With the REST API

This section shows you how to manage scripts used for client-side and server-side scripted authentication, custom policy conditions, and handling OpenID Connect claims by using the REST API.

User-created scripts are realm-specific, hence the URI for the scripts' API can contain a realm component, such as /json{/realm}/scripts. If the realm is not specified in the URI, the top level realm is used.

Tip

OpenAM includes some global example scripts that can be used in any realm.

Scripts are represented in JSON and take the following form. Scripts are built from standard JSON objects and values (strings, numbers, objects, sets, arrays, true, false, and null). Each script has a system-generated universally unique identifier (UUID), which must be used when modifying existing scripts. Renaming a script will not affect the UUID:

{
  "_id": "7e3d7067-d50f-4674-8c76-a3e13a810c33",
  "name": "Scripted Module - Server Side",
  "description": "Default global script for server side Scripted Authentication Module",
  "script": "dmFyIFNUQVJUX1RJ...",
  "language": "JAVASCRIPT",
  "context": "AUTHENTICATION_SERVER_SIDE",
  "createdBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
  "creationDate": 1433147666269,
  "lastModifiedBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
  "lastModifiedDate": 1433147666269
}

The values for the fields shown in the example above are explained below:

_id

The UUID that OpenAM generates for the script.

name

The name provided for the script.

description

An optional text string to help identify the script.

script

The source code of the script. The source code is in UTF-8 format and encoded into Base64.

For example, a script such as the following:

var a = 123;
var b = 456;

When encoded into Base64 becomes:

dmFyIGEgPSAxMjM7IA0KdmFyIGIgPSA0NTY7
language

The language the script is written in - JAVASCRIPT or GROOVY.

Language Support per Context
Script ContextSupported Languages
POLICY_CONDITIONJAVASCRIPT, GROOVY
AUTHENTICATION_SERVER_SIDEJAVASCRIPT, GROOVY
AUTHENTICATION_CLIENT_SIDEJAVASCRIPT
OIDC_CLAIMSJAVASCRIPT, GROOVY

context

The context type of the script.

Supported values are:

POLICY_CONDITION

Policy Condition

AUTHENTICATION_SERVER_SIDE

Server-side Authentication

AUTHENTICATION_CLIENT_SIDE

Client-side Authentication

Note

Client-side scripts must be written in JavaScript.

OIDC_CLAIMS

OIDC Claims

createdBy

A string containing the universal identifier DN of the subject that created the script.

creationDate

An integer containing the creation date and time, in ISO 8601 format.

lastModifiedBy

A string containing the universal identifier DN of the subject that most recently updated the resource type.

If the script has not been modified since it was created, this property will have the same value as createdBy.

lastModifiedDate

A string containing the last modified date and time, in ISO 8601 format.

If the script has not been modified since it was created, this property will have the same value as creationDate.

B.3.4. Querying Scripts

To list all the scripts in a realm, as well as any global scripts, perform an HTTP GET to the /json{/realm}/scripts endpoint with a _queryFilter parameter set to true.

Note

If the realm is not specified in the URL, OpenAM returns scripts in the top level realm, as well as any global scripts.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
  --header "iPlanetDirectoryPro: AQIC5..." \
  https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/scripts?_queryFilter
 =true
{
  "result": [
    {
      "_id": "9de3eb62-f131-4fac-a294-7bd170fd4acb",
      "name": "Scripted Policy Condition",
      "description": "Default global script for Scripted Policy Conditions",
      "script": "LyoqCiAqIFRoaXMg...",
      "language": "JAVASCRIPT",
      "context": "POLICY_CONDITION",
      "createdBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
      "creationDate": 1433147666269,
      "lastModifiedBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
      "lastModifiedDate": 1433147666269
    },
    {
      "_id": "7e3d7067-d50f-4674-8c76-a3e13a810c33",
      "name": "Scripted Module - Server Side",
      "description": "Default global script for server side Scripted Authentication Module",
      "script": "dmFyIFNUQVJUX1RJ...",
      "language": "JAVASCRIPT",
      "context": "AUTHENTICATION_SERVER_SIDE",
      "createdBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
      "creationDate": 1433147666269,
      "lastModifiedBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
      "lastModifiedDate": 1433147666269
    }
  ],
  "resultCount": 2,
  "pagedResultsCookie": null,
  "remainingPagedResults": -1
}
Supported _queryFilter Fields and Operators
FieldSupported Operators
_id Equals (eq), Contains (co), Starts with (sw)
name Equals (eq), Contains (co), Starts with (sw)
description Equals (eq), Contains (co), Starts with (sw)
script Equals (eq), Contains (co), Starts with (sw)
language Equals (eq), Contains (co), Starts with (sw)
context Equals (eq), Contains (co), Starts with (sw)

B.3.5. Reading a Script

To read an individual script in a realm, perform an HTTP GET using the /json{/realm}/scripts endpoint, specifying the UUID in the URL.

Tip

To read a script in the top-level realm, or to read a built-in global script, do not specify a realm in the URL.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
  --header "iPlanetDirectoryPro: AQIC5..." \
  https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/scripts/9de3eb62-f131-4fac-a294-7bd170fd4acb
{
  "_id": "9de3eb62-f131-4fac-a294-7bd170fd4acb",
  "name": "Scripted Policy Condition",
  "description": "Default global script for Scripted Policy Conditions",
  "script": "LyoqCiAqIFRoaXMg...",
  "language": "JAVASCRIPT",
  "context": "POLICY_CONDITION",
  "createdBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
  "creationDate": 1433147666269,
  "lastModifiedBy": "id=dsameuser,ou=user,dc=openam,dc=forgerock,dc=org",
  "lastModifiedDate": 1433147666269
}

B.3.6. Validating a Script

To validate a script, perform an HTTP POST using the /json{/realm}/scripts endpoint, with an _action parameter set to validate. Include a JSON representation of the script and the script language, JAVASCRIPT or GROOVY, in the POST data.

The value for script must be in UTF-8 format and then encoded into Base64.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
  --request POST \
  --header "Content-Type: application/json" \
  --header "iPlanetDirectoryPro: AQIC5..." \
  --data '{
     "script": "dmFyIGEgPSAxMjM7dmFyIGIgPSA0NTY7Cg==",
     "language": "JAVASCRIPT"
  }' \
  https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/scripts/?_action=validate
{
  "success": true
}

If the script is valid the JSON response contains a success key with a value of true.

If the script is invalid the JSON response contains a success key with a value of false, and an indication of the problem and where it occurs, as shown below:

$ curl \
  --request POST \
  --header "Content-Type: application/json" \
  --header "iPlanetDirectoryPro: AQIC5..." \
  --data '{
    "script": "dmFyIGEgPSAxMjM7dmFyIGIgPSA0NTY7ID1WQUxJREFUSU9OIFNIT1VMRCBGQUlMPQo=",
    "language": "JAVASCRIPT"
  }' \
  https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/scripts/?_action=validate
{
  "success": false,
  "errors": [
    {
      "line": 1,
      "column": 27,
      "message": "syntax error"
    }
  ]
}

B.3.7. Creating a Script

To create a script in a realm, perform an HTTP POST using the /json{/realm}/scripts endpoint, with an _action parameter set to create. Include a JSON representation of the script in the POST data.

The value for script must be in UTF-8 format and then encoded into Base64.

Note

If the realm is not specified in the URL, OpenAM creates the script in the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
  --request POST \
  --header "Content-Type: application/json" \
  --header "iPlanetDirectoryPro: AQIC5..." \
  --data '{
     "name": "MyJavaScript",
     "script": "dmFyIGEgPSAxMjM7CnZhciBiID0gNDU2Ow==",
     "language": "JAVASCRIPT",
     "context": "POLICY_CONDITION",
     "description": "An example script"
  }' \
  https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/scripts/?_action
 =create
{
   "_id": "0168d494-015a-420f-ae5a-6a2a5c1126af",
   "name": "MyJavaScript",
   "description": "An example script",
   "script": "dmFyIGEgPSAxMjM7CnZhciBiID0gNDU2Ow==",
   "language": "JAVASCRIPT",
   "context": "POLICY_CONDITION",
   "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
   "creationDate": 1436807766258,
   "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
   "lastModifiedDate": 1436807766258
}

B.3.8. Updating a Script

To update an individual script in a realm, perform an HTTP PUT using the /json{/realm}/scripts endpoint, specifying the UUID in both the URL and the PUT body. Include a JSON representation of the updated script in the PUT data, alongside the UUID.

Note

If the realm is not specified in the URL, OpenAM uses the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
  --header "iPlanetDirectoryPro: AQIC5..." \
  --header "Content-Type: application/json" \
  --request PUT \
  --data '{
    "name": "MyUpdatedJavaScript",
    "script": "dmFyIGEgPSAxMjM7CnZhciBiID0gNDU2Ow==",
    "language": "JAVASCRIPT",
    "context": "POLICY_CONDITION",
    "description": "An updated example script configuration"
  }' \
  https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/scripts/0168d494-015a-420f-ae5a-6a2a5c1126af
{
   "_id": "0168d494-015a-420f-ae5a-6a2a5c1126af",
   "name": "MyUpdatedJavaScript",
   "description": "An updated example script configuration",
   "script": "dmFyIGEgPSAxMjM7CnZhciBiID0gNDU2Ow==",
   "language": "JAVASCRIPT",
   "context": "POLICY_CONDITION",
   "createdBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
   "creationDate": 1436807766258,
   "lastModifiedBy": "id=amadmin,ou=user,dc=openam,dc=forgerock,dc=org",
   "lastModifiedDate": 1436808364681
}

B.3.9. Deleting a Script

To delete an individual script in a realm, perform an HTTP DELETE using the /json{/realm}/scripts endpoint, specifying the UUID in the URL.

Note

If the realm is not specified in the URL, OpenAM uses the top level realm.

The iPlanetDirectoryPro header is required and should contain the SSO token of an administrative user, such as amAdmin, who has access to perform the operation.

$ curl \
  --request DELETE \
  --header "iPlanetDirectoryPro: AQIC5..." \
  https://openam.example.com:8443/openam/json/realms/root/realms/myrealm/scripts/0168d494-015a-420f-ae5a-6a2a5c1126af
{}

B.4. Scripting

amster type ID: scripting

B.4.1. Configuration

The following settings appear on the Configuration tab:

Default Script Type

The default script context type when creating a new script.

The possible values for this property are:

POLICY_CONDITION
AUTHENTICATION_SERVER_SIDE
AUTHENTICATION_CLIENT_SIDE
OIDC_CLAIMS

Default value: POLICY_CONDITION

amster data attribute: defaultContext

B.4.2. Secondary Configurations

This service has the following Secondary Configurations.

B.4.2.1. Engine Configuration

The following properties are available for Scripting Service secondary configuration instances:

Engine Configuration

Configure script engine parameters for running a particular script type in OpenAM.

amster data attribute: engineConfiguration

To access a secondary configuration instance using the ssoadm command, use: --subconfigname [primary configuration]/[secondary configuration] For example:

$ ssoadm set-sub-cfg \
  --adminid amAdmin \
  --password-file admin_pwd_file \
  --servicename ScriptingService \
  --subconfigname OIDC_CLAIMS/engineConfiguration \
  --operation set \
  --attributevalues maxThreads=300 queueSize=-1

Note

Supports server-side scripts only. OpenAM cannot configure engine settings for client-side scripts.

The configurable engine settings are as follows:

Server-side Script Timeout

The maximum execution time any individual script should take on the server (in seconds). OpenAM terminates scripts which take longer to run than this value.

amster data attribute: serverTimeout

Core thread pool size

The initial number of threads in the thread pool from which scripts operate. OpenAM will ensure the pool contains at least this many threads.

amster data attribute: coreThreads

Maximum thread pool size

The maximum number of threads in the thread pool from which scripts operate. If no free thread is available in the pool, OpenAM creates new threads in the pool for script execution up to the configured maximum.

amster data attribute: maxThreads

Thread pool queue size

The number of threads to use for buffering script execution requests when the maximum thread pool size is reached.

amster data attribute: queueSize

Thread idle timeout (seconds)

Length of time (in seconds) for a thread to be idle before OpenAM terminates created threads. If the current pool size contains the number of threads set in Core thread pool size idle threads will not be terminated, to maintain the initial pool size.

amster data attribute: idleTimeout

Java class whitelist

Specifies the list of class-name patterns allowed to be invoked by the script. Every class accessed by the script must match at least one of these patterns.

You can specify the class name as-is or use a regular expression.

amster data attribute: whiteList

Java class blacklist

Specifies the list of class-name patterns that are NOT allowed to be invoked by the script. The blacklist is applied AFTER the whitelist to exclude those classes - access to a class specified in both the whitelist and the blacklist will be denied.

You can specify the class name to exclude as-is or use a regular expression.

amster data attribute: blackList

Use system SecurityManager

If enabled, OpenAM will make a call to System.getSecurityManager().checkPackageAccess(...) for each class that is accessed. The method throws SecurityException if the calling thread is not allowed to access the package.

Note

This feature only takes effect if the security manager is enabled for the JVM.

amster data attribute: useSecurityManager

Scripting languages

Select the languages available for scripts on the chosen type. Either GROOVY or JAVASCRIPT.

amster data attribute: languages

Default Script

The source code that is presented as the default when creating a new script of this type.

amster data attribute: defaultScript

Appendix C. Getting Support

For more information or resources about AM and ForgeRock Support, see the following sections:

C.1. Accessing Documentation Online

ForgeRock publishes comprehensive documentation online:

  • The ForgeRock Knowledge Base offers a large and increasing number of up-to-date, practical articles that help you deploy and manage ForgeRock software.

    While many articles are visible to community members, ForgeRock customers have access to much more, including advanced information for customers using ForgeRock software in a mission-critical capacity.

  • ForgeRock product documentation, such as this document, aims to be technically accurate and complete with respect to the software documented. It is visible to everyone and covers all product features and examples of how to use them.

C.2. Using the ForgeRock.org Site

The ForgeRock.org site has links to source code for ForgeRock open source software, as well as links to the ForgeRock forums and technical blogs.

If you are a ForgeRock customer, raise a support ticket instead of using the forums. ForgeRock support professionals will get in touch to help you.

C.3. Getting Support and Contacting ForgeRock

ForgeRock provides support services, professional services, training through ForgeRock University, and partner services to assist you in setting up and maintaining your deployments. For a general overview of these services, see https://www.forgerock.com.

ForgeRock has staff members around the globe who support our international customers and partners. For details on ForgeRock's support offering, including support plans and service level agreements (SLAs), visit https://www.forgerock.com/support.

Glossary

Access control

Control to grant or to deny access to a resource.

Account lockout

The act of making an account temporarily or permanently inactive after successive authentication failures.

Actions

Defined as part of policies, these verbs indicate what authorized subjects can do to resources.

Advice

In the context of a policy decision denying access, a hint to the policy enforcement point about remedial action to take that could result in a decision allowing access.

Agent administrator

User having privileges only to read and write policy agent profile configuration information, typically created to delegate policy agent profile creation to the user installing a policy agent.

Agent authenticator

Entity with read-only access to multiple agent profiles defined in the same realm; allows an agent to read web service profiles.

Application

In general terms, a service exposing protected resources.

In the context of AM policies, the application is a template that constrains the policies that govern access to protected resources. An application can have zero or more policies.

Application type

Application types act as templates for creating policy applications.

Application types define a preset list of actions and functional logic, such as policy lookup and resource comparator logic.

Application types also define the internal normalization, indexing logic, and comparator logic for applications.

Attribute-based access control (ABAC)

Access control that is based on attributes of a user, such as how old a user is or whether the user is a paying customer.

Authentication

The act of confirming the identity of a principal.

Authentication chaining

A series of authentication modules configured together which a principal must negotiate as configured in order to authenticate successfully.

Authentication level

Positive integer associated with an authentication module, usually used to require success with more stringent authentication measures when requesting resources requiring special protection.

Authentication module

AM authentication unit that handles one way of obtaining and verifying credentials.

Authorization

The act of determining whether to grant or to deny a principal access to a resource.

Authorization Server

In OAuth 2.0, issues access tokens to the client after authenticating a resource owner and confirming that the owner authorizes the client to access the protected resource. AM can play this role in the OAuth 2.0 authorization framework.

Auto-federation

Arrangement to federate a principal's identity automatically based on a common attribute value shared across the principal's profiles at different providers.

Bulk federation

Batch job permanently federating user profiles between a service provider and an identity provider based on a list of matched user identifiers that exist on both providers.

Circle of trust

Group of providers, including at least one identity provider, who have agreed to trust each other to participate in a SAML v2.0 provider federation.

Client

In OAuth 2.0, requests protected web resources on behalf of the resource owner given the owner's authorization. AM can play this role in the OAuth 2.0 authorization framework.

Conditions

Defined as part of policies, these determine the circumstances under which which a policy applies.

Environmental conditions reflect circumstances like the client IP address, time of day, how the subject authenticated, or the authentication level achieved.

Subject conditions reflect characteristics of the subject like whether the subject authenticated, the identity of the subject, or claims in the subject's JWT.

Configuration datastore

LDAP directory service holding AM configuration data.

Cross-domain single sign-on (CDSSO)

AM capability allowing single sign-on across different DNS domains.

Delegation

Granting users administrative privileges with AM.

Entitlement

Decision that defines which resource names can and cannot be accessed for a given subject in the context of a particular application, which actions are allowed and which are denied, and any related advice and attributes.

Extended metadata

Federation configuration information specific to AM.

Extensible Access Control Markup Language (XACML)

Standard, XML-based access control policy language, including a processing model for making authorization decisions based on policies.

Federation

Standardized means for aggregating identities, sharing authentication and authorization data information between trusted providers, and allowing principals to access services across different providers without authenticating repeatedly.

Fedlet

Service provider application capable of participating in a circle of trust and allowing federation without installing all of AM on the service provider side; AM lets you create Java Fedlets.

Hot swappable

Refers to configuration properties for which changes can take effect without restarting the container where AM runs.

Identity

Set of data that uniquely describes a person or a thing such as a device or an application.

Identity federation

Linking of a principal's identity across multiple providers.

Identity provider (IdP)

Entity that produces assertions about a principal (such as how and when a principal authenticated, or that the principal's profile has a specified attribute value).

Identity repository

Data store holding user profiles and group information; different identity repositories can be defined for different realms.

Java EE policy agent

Java web application installed in a web container that acts as a policy agent, filtering requests to other applications in the container with policies based on application resource URLs.

Metadata

Federation configuration information for a provider.

Policy

Set of rules that define who is granted access to a protected resource when, how, and under what conditions.

Policy Agent

Agent that intercepts requests for resources, directs principals to AM for authentication, and enforces policy decisions from AM.

Policy Administration Point (PAP)

Entity that manages and stores policy definitions.

Policy Decision Point (PDP)

Entity that evaluates access rights and then issues authorization decisions.

Policy Enforcement Point (PEP)

Entity that intercepts a request for a resource and then enforces policy decisions from a PDP.

Policy Information Point (PIP)

Entity that provides extra information, such as user profile attributes that a PDP needs in order to make a decision.

Principal

Represents an entity that has been authenticated (such as a user, a device, or an application), and thus is distinguished from other entities.

When a Subject successfully authenticates, AM associates the Subject with the Principal.

Privilege

In the context of delegated administration, a set of administrative tasks that can be performed by specified subjects in a given realm.

Provider federation

Agreement among providers to participate in a circle of trust.

Realm

AM unit for organizing configuration and identity information.

Realms can be used for example when different parts of an organization have different applications and user data stores, and when different organizations use the same AM deployment.

Administrators can delegate realm administration. The administrator assigns administrative privileges to users, allowing them to perform administrative tasks within the realm.

Resource

Something a user can access over the network such as a web page.

Defined as part of policies, these can include wildcards in order to match multiple actual resources.

Resource owner

In OAuth 2.0, entity who can authorize access to protected web resources, such as an end user.

Resource server

In OAuth 2.0, server hosting protected web resources, capable of handling access tokens to respond to requests for such resources.

Response attributes

Defined as part of policies, these allow AM to return additional information in the form of "attributes" with the response to a policy decision.

Role based access control (RBAC)

Access control that is based on whether a user has been granted a set of permissions (a role).

Security Assertion Markup Language (SAML)

Standard, XML-based language for exchanging authentication and authorization data between identity providers and service providers.

Service provider (SP)

Entity that consumes assertions about a principal (and provides a service that the principal is trying to access).

Session

The interval that starts with the user authenticating through AM and ends when the user logs out, or when their session is terminated. For browser-based clients, AM manages user sessions across one or more applications by setting a session cookie. See also Stateful session and Stateless session.

Session high availability

Capability that lets any AM server in a clustered deployment access shared, persistent information about users' sessions from the CTS token store. The user does not need to log in again unless the entire deployment goes down.

Session token

Unique identifier issued by AM after successful authentication. For a Stateful session, the session token is used to track a principal's session.

Single log out (SLO)

Capability allowing a principal to end a session once, thereby ending her session across multiple applications.

Single sign-on (SSO)

Capability allowing a principal to authenticate once and gain access to multiple applications without authenticating again.

Site

Group of AM servers configured the same way, accessed through a load balancer layer.

The load balancer handles failover to provide service-level availability. Use sticky load balancing based on amlbcookie values to improve site performance.

The load balancer can also be used to protect AM services.

Standard metadata

Standard federation configuration information that you can share with other access management software.

Stateful session

An AM session that resides in the Core Token Service's token store. Stateful sessions might also be cached in memory on one or more AM servers. AM tracks stateful sessions in order to handle events like logout and timeout, to permit session constraints, and to notify applications involved in SSO when a session ends.

Stateless session

An AM session for which state information is encoded in AM and stored on the client. The information from the session is not retained in the CTS token store. For browser-based clients, AM sets a cookie in the browser that contains the session information.

Subject

Entity that requests access to a resource

When a subject successfully authenticates, AM associates the subject with the Principal that distinguishes it from other subjects. A subject can be associated with multiple principals.

User data store

Data storage service holding principals' profiles; underlying storage can be an LDAP directory service, a relational database, or a custom IdRepo implementation.

Web policy agent

Native library installed in a web server that acts as a policy agent with policies based on web page URLs.

Read a different version of :