Access Management 7.2.2

Access token modification plugin

Use this extension point to modify the key-value pairs in an OAuth 2.0 access token. For example, you could make a REST call to an external service, and add or change a key-value pair in the access token based on the response, before issuing the token to the resource owner.

Default script

To view the default script, including the available script properties, see oauth2-access-token-modification.groovy.

To view or modify the default script in the AM admin UI, go to Realms > Realm Name > Scripts and select OAuth2 Access Token Modification Script.

Java interface

org.forgerock.oauth2.core.plugins.AccessTokenModifier

Java sample
Show Sample Code
/*
 * Copyright 2021-2022 ForgeRock AS. All Rights Reserved
 *
 * Use of this code requires a commercial software license with ForgeRock AS.
 * or with one of its affiliates. All use shall be exclusively subject
 * to such license between the licensee and ForgeRock AS.
 */

package org.forgerock.openam.examples;

import org.forgerock.oauth2.core.AccessToken;
import org.forgerock.oauth2.core.OAuth2Request;
import org.forgerock.oauth2.core.plugins.AccessTokenModifier;

/**
 * Custom implementation of the Access Token Modifier
 * plugin interface {@link org.forgerock.oauth2.core.plugins.AccessTokenModifier}
 *
 * <li>
 * In this example the {@code modifyAccessToken} method adds an additional field to the token.
 * </li>
 *
 */
public class CustomAccessTokenModifier implements AccessTokenModifier {

    @Override
    public void modifyAccessToken(AccessToken accessToken, OAuth2Request request) {
        //Field to always include in token
        accessToken.setField("additional", "field");
    }
}

About modifying access tokens

You can modify both client-side and server-side access tokens. Modifications are stored permanently in either the issued JWT for client-side tokens, or in the CTS for server-side access tokens. You can also modify macaroons used in place of regular tokens. In this case, you implement the plugin to modify the key pairs in the token, and optionally, to add caveats. For more information, see the MacaroonToken interface.

When issuing modified access tokens, consider the following important points:

  • Removing or changing native properties may render the access token unusable.

    AM requires that certain native properties are present in the access token in order to consider it valid. Removing or modifying these properties may cause the OAuth 2.0 flows to break.

    Native properties are marked in the AM Public API Javadoc with a warning about loss of functionality if they are edited or removed.

  • Modifying access tokens affects the size of the client-side token or server-side entry.

    Changes made to OAuth 2.0 access tokens directly impacts the size of the server-side tokens, or the size of the JSON web tokens (JWT) if client-side tokens are enabled.

    You must ensure that the token size remains within your client or user-agent size limits.

    For more information, see Token storage location.

Example access token modification plugin

Complete the following steps to implement a custom access token modification script that sets additional properties in the access token:

To configure AM to use a Java access token modification plugin, see Configure AM to use a Java OAuth 2.0 plugin.

Prepare AM to modify access tokens

The script requires that the authenticated user of the access token has an email address and telephone number in their profile. The script adds the values of these fields to the access token.

  1. Log in as an AM administrator.

    For example, amAdmin.

  2. Add an email address and telephone number value to the demo user’s profile.

    The access token modification script injects the values provided into the OAuth 2.0 access token before it is issued to the resource owner.

    1. Select Realms > Realm Name > Identities.

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

    3. In Email Address, enter a valid address. For example, demo.user@example.com.

    4. In Telephone Number, enter a value. For example, 44 117 496 0228.

    5. Save your changes.

  3. Modify the default access token modification script to set additional fields.

    1. Go to Realms > Realm Name > Scripts, and click OAuth2 Access Token Modification Script.

    2. In the Script field:

      • Uncomment the following line, by surrounding with a pair of */ and /* strings:

        /* ... */
        accessToken.setField("hello", "world")
        /* ... */
      • Similarly, uncomment these lines:

        /* ... */
        def attributes = identity.getAttributes(["mail", "telephoneNumber"].toSet())
        accessToken.setField("mail", attributes["mail"])
        accessToken.setField("phone", attributes["telephoneNumber"])
        /* ... */

        To include additional data in the /oauth2/access_token response, edit your script to call the addExtraData method. For example:

        accessToken.addExtraData("hello", "world")

        This will return the data as part of the response body in the following way:

        {
          "access_token":"sbQZuveFumUDV5R1vVBl6QAGNB8",
          "hello":"world",
          "scope":"write",
          "token_type":"Bearer",
          "expires_in":3599
        }
    3. Save your changes.

Configure AM to use the custom access token modification script

Perform this task to set up an OAuth 2.0 provider that uses the modified default access token modification script.

  1. Log in to the AM admin UI as an administrator.

    For example, amAdmin.

  2. Configure the provider to ensure the following properties are set:

    • Access Token Modification Plugin Type to SCRIPTED.

    • Access Token Modification Plugin Script to OAuth2 Access Token Modification Script.

    By default, a new OAuth 2.0 provider uses the default access token modification script.

  3. Save your changes.

Create an OAuth2 client for authorization

Create an OAuth 2.0 client to use in the authorization request.

  1. In the AM admin UI, go to Realms > Realm Name > Applications > OAuth 2.0 > Clients, and click Add Client.

  2. Enter the following values:

    • Client ID: myClient

    • Client secret: forgerock

    • Redirection URIs: https://www.example.com:443/callback

    • Scope(s): access|Access to your data

  3. Click Create.

AM is now configured to issue access tokens using the default access token modification script. As the demo user, you can now obtain an access token to test the script functionality.

Try the custom access token modification script

This section demonstrates obtaining an OAuth 2.0 access token that has been modified by a script.

First, use the Authorization code grant flow to authenticate with AM as the resource owner, allow the client to access profile data, and receive the authorization code.

Next, exchange the authorization code for an access token.

The access token will have been altered by the default access token modification script to include:

  • The resource owner’s telephone number and email address, taken from their profile in AM, which is acting as the authorization server.

  • A hello:world key-value pair.

Finally, use the introspect endpoint to verify that the access token includes the modified values.

Obtain an authorization code

  1. In a web browser, go to the /oauth2/authorize endpoint, including the parameters and values configured for the OAuth 2.0 client in the previous section.

    Make sure you specify the correct realm in the endpoint. For example, if the OAuth 2.0 provider is configured for the /alpha realm, then use /oauth2/realms/root/realms/alpha/authorize.

    For example:

    https://openam.example.com:8443/openam/oauth2/realms/root/realms/alpha/authorize \
    ?client_id=myClient \
    &response_type=code \
    &scope=access \
    &state=abc123 \
    &redirect_uri=https://www.example.com:443/callback

    Note that the URL is split for readability purposes.

    The AM login page is displayed.

  2. Log in as the demo user, with password Ch4ng31t.

    The AM OAuth 2.0 consent page is displayed.

  3. Review the scopes being requested, and click Allow.

    AM redirects the browser to the location specified in the redirect_uri parameter, https://www.example.com:443/callback in this example, and appends a number of query parameters.

    For example:

    OAuth 2.0 authorization code in browser URL bar.
  4. Record the value of the code query parameter.

    This is the authorization code and is exchanged for an access token in the next procedure.

Exchange an authorization code for an access token

  1. Send a POST request to the /oauth2/access_token endpoint, including the authorization code obtained in the previous procedure, and the parameters and values configured for the OAuth 2.0 client earlier.

    For example:

    $ curl \
      --request POST \
      --data "grant_type=authorization_code" \
      --data "code=tH_s2obVRt2_yB6x4OxH1J3eMkU" \
      --data "client_id=myClient" \
      --data "client_secret=forgerock" \
      --data "redirect_uri=https://www.example.com:443/callback" \
      "https://openam.example.com:8443/openam/oauth2/realms/root/realms/alpha/access_token"
    {
      "access_token": "sbQZuveFumUDV5R1vVBl6QAGNB8",
      "scope": "access",
      "token_type": "Bearer",
      "expires_in": 3599
    }
  2. Record the value of the access_token property.

    This is the access token, the properties of which have been modified by the access token modification script. Follow the steps in the next procedure to introspect the token to verify the properties have been modified.

Introspect an access token to verify access token modification

  1. Send a POST request to the /oauth2/introspect endpoint, including the access token obtained in the previous procedure, and the credentials of the OAuth 2.0 client.

    For example:

    $ curl \
      --request POST \
      --data "client_id=myClient" \
      --data "client_secret=forgerock" \
      --data "token=sbQZuveFumUDV5R1vVBl6QAGNB8" \
      "https://openam.example.com:8443/openam/oauth2/realms/root/realms/alpha/introspect"
    {
      "active": true,
      "scope": "access",
      "client_id": "myClient",
      "user_id": "demo",
      "username":"demo",
      "token_type": "Bearer",
      "exp": 1556289970,
      "sub": "(usr!demo)",
      "subname": "demo",
      "iss": "https://openam.example.com:8443/openam/oauth2",
      "auth_level": 0,
      "auditTrackingId": "c6e22be7-6166-402b-9d72-a03134f08c22-8605",
      "hello": "world",
      "mail": [
        "demo.user@example.com"
      ],
      "phone": [
        "+44 117 496 0228"
      ]
    }

    Notice that the output includes a hello:world key-value pair, as well as mail and phone properties, containing values taken from the user’s profile data.

OAuth 2.0 access token modification scripting API

The following properties are available to access token modification scripts, in addition to the common OAuth 2.0 properties.

Show script properties
accessToken

The access token to be updated.

clientProperties

A map of properties configured in the relevant client profile. Only present if the client was correctly identified.

The keys in the map are as follows:

clientId

The URI of the client.

allowedGrantTypes

The list of the allowed grant types (org.forgerock.oauth2.core.GrantType) for the client.

allowedResponseTypes

The list of the allowed response types for the client.

allowedScopes

The list of the allowed scopes for the client.

customProperties

A map of any custom properties added to the client.

Lists or maps are included as sub-maps. For example, a custom property of customMap[Key1]=Value1 is returned as customMap > Key1 > Value1.

To add custom properties to a client, go to OAuth 2.0 > Clients > Client ID > Advanced, and then update the Custom Properties field.

requestProperties

A map of the properties present in the request. Always present.

The keys in the map are as follows:

requestUri

The URI of the request.

realm

The realm to which the request was made.

requestParams

The request parameters, and/or posted data. Each value in this map is a list of one, or more, properties.

To mitigate the risk of reflection-type attacks, use OWASP best practices when handling these properties. For example, see Unsafe use of Reflection.

scopes

Contains a set of the requested scopes. For example:

[
  "read",
  "transfer",
  "download"
]
session

Contains a representation of the user’s session object if the request contained a session cookie.

For more details, see the com.iplanet.sso.SSOToken class in the ForgeRock Access Management Javadoc.