---
title: Access tokens
description: Use this extension point to modify the key-value pairs in an OAuth 2.0 access token before Advanced Identity Cloud issues it.
component: pingoneaic
page_id: pingoneaic:am-oauth2:plugins-access-token-modifier
canonical_url: https://docs.pingidentity.com/pingoneaic/am-oauth2/plugins-access-token-modifier.html
keywords: ["OAuth 2.0", "Customization", "Scripting", "Plugins"]
page_aliases: ["oauth2-guide:plugins-access-token-modifier.adoc"]
section_ids:
  constraints: Constraints
  examples: Examples
  example-atm-legacy: Add profile data to access token (legacy script)
  update-profile-data: Prepare the resource owner profile
  prepare-atm-legacy: Create the script
  create-client-legacy: Use the script
  test-atm-legacy: Test the script
  example-atm-nextgen: Add external data to access token (next-generation script)
  create-resource-owner: Create the resource owner profile
  prepare-atm-nextgen: Create the script
  configure-atm-nextgen: Use the script
  test-atm-nextgen: Test the script
  use_a_validated_script: Use a validated script
---

# Access tokens

Use this extension point to modify the key-value pairs in an OAuth 2.0 access token before Advanced Identity Cloud issues it.

* Template script

  [OAuth2 Access Token Modification Script](../am-scripting/sample-scripts.html#oauth2-access-token-modification-js)

* Script bindings

  [Access token modification scripting API](../am-scripting/access-token-modification-api.html)

The examples on this page use a script to add data to an access token.

## Constraints

You can modify both [client-side](client-side-tokens.html) and [server-side](server-side-tokens.html) access tokens. You can also modify [macaroons](oauth2-macaroons.html) used in place of regular tokens.

Advanced Identity Cloud stores the modifications in client-side and server-side access tokens. When issuing modified access tokens, consider the following constraints:

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

  Advanced Identity Cloud relies on native properties that it includes in the access token. If you remove or modify those properties, Advanced Identity Cloud considers the access token invalid. This can cause the OAuth 2.0 flows to break.

* Modifying access tokens can significantly increase the size of the token.

  Adding key-value pairs to OAuth 2.0 access tokens affects the size of client-side JSON web tokens (JWT), or the size of server-side tokens, if enabled.

  Make sure the modified tokens fit within your client and user-agent size limits.

Learn more in [Token storage](token-storage.html).

## Examples

The following examples use JavaScript in either a legacy or next-generation scripting environment to modify the access token.

* [Add profile data to access token (legacy script)](#example-atm-legacy)

* [Add external data to access token (next-generation script)](#example-atm-nextgen)

### Add profile data to access token (legacy script)

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

1. [Prepare the resource owner profile](#update-profile-data)

2. [Create the script](#prepare-atm-legacy)

3. [Use the script](#create-client-legacy)

4. [Test the script](#test-atm-legacy)

#### Prepare the resource owner profile

An OAuth 2.0 client requests the access token on behalf of a resource owner.

The script requires that the authenticated resource owner has an email address and telephone number in their profile.

The script adds the values of these fields to the access token.

1. [Create a resource owner profile](../identities/manage-identities.html#create_a_user_profile) and record the username and password.

2. Update the following settings in the new user profile and save your work:

   * Email Address

     `user@example.com`

   * Telephone Number

     `(555) 323-1234`

#### Create the script

1. In the Advanced Identity Cloud admin console, [create a script](../developer-docs/scripting-auth.html#create-a-new-auth-script) of type OAuth2 Access Token Modification.

2. Replace the default JavaScript with the following script:

   ```javascript
   (function () {
     // Add a field next to the access token in the /oauth2/access_token response.
     accessToken.addExtraData('hello', 'world');

     // Add identity profile attribute values to the /oauth2/introspect response.
     accessToken.setField('mail', identity.getAttribute('mail'));
     accessToken.setField('phone', identity.getAttribute('telephoneNumber').toArray()[0]);

     // No return value is expected.
   }());
   ```

   The `accessToken` methods update the access token before Advanced Identity Cloud issues it.

   The `identity` methods get attribute values from the resource owner's profile.

   Learn more in the [Access token modification scripting API](../am-scripting/access-token-modification-api.html).

#### Use the script

The OAuth 2.0 client profile in this example overrides the OAuth 2.0 provider settings. This lets you test the script without affecting access tokens issued to other clients.

1. [Create an OIDC/ OAuth 2.0 web client application](../app-management/register-a-custom-application.html#register_a_custom_application_or_service) with the following settings:

   * Name and Client ID

     `myClient`

   * Client Secret

     `mySecret`

   * Sign-in URLs

     `https://www.example.com:443/callback`

   * Scopes

     `access`

2. [Override OAuth 2.0 provider settings](plugins-customize.html#override-oauth2-provider-settings) for this client with the access token modification values.

#### Test the script

The example uses the [Authorization code grant](oauth2-authz-grant.html) flow:

* The resource owner authenticates to obtain an SSO token.

* The client relies on Implied Consent being enabled (default). It assumes the resource owner grants the client access.

* The client requests the authorization code and exchanges it for an access token your script modified.

* The client introspects the access token.

* The client requests the authorization code and exchanges it for an access token that's modified by your script. Follow these steps:

  1. [Get an authorization code](oauth2-authz-grant.html#proc-auth-code-browser) using the values configured for `myClient` and the resource owner's login credentials.

  2. [Exchange the authorization code for an access token](oauth2-authz-grant.html#proc-auth-code-token) providing the authorization code and the values for `myClient`.

     For example:

     ```bash
     curl \
     --request POST \
     --user 'myClient:mySecret' \
     --data 'grant_type=authorization_code' \
     --data 'code=<authorization-code>' \
     --data 'redirect_uri=https://www.example.com:443/callback' \
     'https://<tenant-env-fqdn>/am/oauth2/realms/root/realms/alpha/access_token'
     {
       "access_token": "<access-token>",
       "refresh_token": "<refresh-token>",
       "scope": "access",
       "hello": "world",
       "token_type": "Bearer",
       "expires_in": 3599
     }
     ```

  The script added `"hello": "world"` alongside the access token in the [/oauth2/access\_token](oauth2-access_token-endpoint.html) response.

  1. Make an HTTP call to [/oauth2/introspect](oauth2-introspect-endpoint.html) to verify that the access token includes the values for `mail` and `phone` from the resource owner's profile.

     For example:

     ```bash
     curl \
     --request POST \
     --user 'myClient:mySecret' \
     --data 'token=<access-token>' \
     'https://<tenant-env-fqdn>/am/oauth2/realms/root/realms/alpha/introspect'
     {
       …​
       "mail": ["user@example.com"],
       "phone": "(555) 323-1234"
       …​
     }
     ```

### Add external data to access token (next-generation script)

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

1. [Create the resource owner profile](#create-resource-owner)

2. [Create the script](#prepare-atm-nextgen)

3. [Use the script](#configure-atm-nextgen)

4. [Test the script](#test-atm-nextgen)

#### Create the resource owner profile

An OAuth 2.0 client requests the access token on behalf of a resource owner.

1. [Create a resource owner profile](../identities/manage-identities.html#create_a_user_profile) and record the username and password.

#### Create the script

Write a script that does the following:

* Calls an external API to set values for browser and IP in the access token

* Sets a new expiry time in the access token and in the resource owner's profile data

* Generates random UUIDs to return in the JSON response

1. Under Native Consoles > Access Management, go to Realms > *Realm Name* > Scripts, and click +New Script.

2. Provide a suitable name for your script and select the following values:

   * Script Type

     `OAuth2 Access Token Modification`

   * Evaluator Version

     `Next Generation`

3. Click Create.

4. Replace the default JavaScript with the following script:

   ```java
   // use httpclient to call external API
   var options = {
     method: "GET",
     headers: {
       "Content-Type": "application/json; charset=UTF-8"
     }
   };
   var response = httpClient.send("https://dummyjson.com/ip", options).get();
   if (response.status === 200) {
   	var ipInfo = response.json();
     // add values to the token
     accessToken.setField("browser", ipInfo.userAgent);
     accessToken.setField('ip', ipInfo.ip);

   } else {
     logger.error("Error getting IP and browser info: " + response.statusText);
   }

   // set a shorter expiry time
   var newExpiry = Date.now() + 300000;
   accessToken.setExpiryTime(newExpiry);

   // update profile data using the openidm binding
   var userID = identity.getAttributeValues("_id")[0];
   var user = openidm.read("managed/alpha_user/" + userID);
   user.description = "New access token expiry time: " + newExpiry;
   var updatedUser = openidm.update("managed/alpha_user/" + userID, null, user);

   // use utils binding to get random values
   var uids = [0,0,0];
   utils.crypto.getRandomValues(uids);

   // add values to be returned in the JSON response
   accessToken.addExtraJsonData('uids', uids);
   ```

   |   |                                                                                                                                                                                                                                                                                                                                                |
   | - | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
   |   | You can find information about the common bindings such as `httpClient` and `utils` in [Common bindings](../am-scripting/script-bindings.html).You can find information about the bindings specific to access token modification scripts in the [Access token modification scripting API](../am-scripting/access-token-modification-api.html). |

5. Save your changes.

#### Use the script

The OAuth 2.0 client profile in this example overrides the OAuth 2.0 provider settings. This lets you test the script without affecting access tokens issued to other clients.

1. [Create an OIDC/ OAuth 2.0 web client application](../app-management/register-a-custom-application.html#register_a_custom_application_or_service) with the following settings:

   * Name and Client ID

     `myClient`

   * Client Secret

     `mySecret`

   * Sign-in URLs

     `https://www.example.com:443/callback`

   * Scopes

     `access`

2. [Override OAuth 2.0 provider settings](plugins-customize.html#override-oauth2-provider-settings) for this client with the access token modification values.

#### Test the script

The example uses the [Authorization code grant](oauth2-authz-grant.html) flow:

* The resource owner authenticates to obtain an SSO token.

* The client relies on Implied Consent being enabled (default). It assumes the resource owner grants the client access.

* The client requests the authorization code and exchanges it for an access token your script modified.

* The client introspects the access token.

* The client requests the authorization code and exchanges it for an access token that's modified by your script. Follow these steps:

  1. [Get an authorization code](oauth2-authz-grant.html#proc-auth-code-browser) using the values configured for `myClient` and the resource owner's login credentials.

  2. [Exchange the authorization code for an access token](oauth2-authz-grant.html#proc-auth-code-token) providing the authorization code and the values for `myClient`.

     The response includes the JSON data (`uuids`) added by the script and the updated expiry time:

     ```json
     {
         "access_token": "anmKKgqxNkTMMGVRF2aOR3D2cCc",
         "uids": [
               841804401,
               732387389,
               290315868
           ],
         "scope": "access",
         "token_type": "Bearer",
         "expires_in": 299
         ]
     }
     ```

  3. Make an HTTP call [/oauth2/introspect](oauth2-introspect-endpoint.html) to verify that the access token includes the modified values for `browser`, `ip`, and `exp`. For example:

     ```json
     {
         {
             "active": true,
             "scope": "access",
             "realm": "/alpha",
             "client_id": "myClient",
             "user_id": "bjensen",
             ...
             "exp": 1755108160,
             "browser": "Apache-HttpAsyncClient/4.1.4 (Java/17.0.10)",
             "ip": "1.70.145.10"
         }
     }
     ```

## Use a validated script

Test your access token modification scripts as you did in the examples.

After validating your script by overriding the OAuth 2.0 provider settings with a test client, you can update Advanced Identity Cloud to use your script in one of the following ways:

* [Configure the OAuth 2.0 provider](plugins-customize.html#use-custom-oauth2-plugin) with the access token modification extension settings.

* In the Advanced Identity Cloud admin console, select Scripts > Auth Scripts > OAuth2 Access Token Modification Script, and replace the script content with your validated script.
