AM 7.2.2

User info claims plugin

This plugin extension point is invoked when issuing an ID token or during a request to the /userinfo OpenID Connect endpoint. Use this script to retrieve claim values based on an issued access token.

Default script

To view the default script, including the available script properties, see oidc-claims-extension.groovy.

To view or modify the default script in the AM admin UI, go to Realms > Realm Name > Scripts and select OIDC Claims Script.

Java interface

org.forgerock.oauth2.core.plugins.UserInfoClaimsPlugin

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 java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.forgerock.oauth2.core.AccessToken;
import org.forgerock.oauth2.core.ClientRegistration;
import org.forgerock.oauth2.core.OAuth2Request;
import org.forgerock.oauth2.core.UserInfoClaims;
import org.forgerock.oauth2.core.plugins.UserInfoClaimsPlugin;

/**
 * Custom implementation of the User Info Claims
 * plugin interface {@link org.forgerock.oauth2.core.plugins.UserInfoClaimsPlugin}
 *
 * <li>
 * The {@code getUserInfo} method
 * populates scope values and sets the resource owner ID to return.
 * </li>
 *
 */
public class CustomUserInfoClaimsPlugin implements UserInfoClaimsPlugin {

    @Override
    public UserInfoClaims getUserInfo(ClientRegistration clientRegistration, AccessToken token, OAuth2Request request) {
        Map<String, Object> response = mapScopes(token);
        response.put("sub", token.getResourceOwnerId());
        UserInfoClaims userInfoClaims = new UserInfoClaims(response, null);
        return userInfoClaims;
    }

    /**
     * Set read and write permissions according to scope.
     *
     * @param token The access token presented for validation.
     * @return The map of read and write permissions,
     *         with permissions set to {@code true} or {@code false},
     *         as appropriate.
     */
    private Map<String, Object> mapScopes(AccessToken token) {
        Set<String> scopes = token.getScope();
        Map<String, Object> map = new HashMap<String, Object>();
        final String[] permissions = {"read", "write"};

        for (String scope : permissions) {
            if (scopes.contains(scope)) {
                map.put(scope, true);
            } else {
                map.put(scope, false);
            }
        }
        return map;
    }
}

Example user info claims plugin

Complete the following steps to implement an example user info claims script that adds a custom claim to the profile scope:

This example is implemented using a script. For a version that uses Java, see How do I add custom claims to the OIDC Claims Script.

Configure the user info claims script

This task describes how to modify the default script to map a custom claim. If you prefer to create a new script, refer to the steps described in Manage scripts (UI), and reference the new script name when you configure the provider.

  1. In the AM admin UI, go to Realms > Realm Name > Scripts, and click OIDC Claims Script.

  2. In the Script field:

    • Add a new claim to the script. As a simple example, insert myTestName after the name claim in the claimAttributes section, as follows:

      claimAttributes = [
          "email": userProfileClaimResolver.curry("mail"),
          ...
          "name": userProfileClaimResolver.curry("cn"),
          "myTestName": userProfileClaimResolver.curry("cn")
      ]
    • Add the new claim to the profile scope in the claims map:

      scopeClaimsMap = [
          "email": [ "email" ],
          ...
          "profile": [ "given_name", "zoneinfo", "family_name", "locale", "name", "myTestName" ]

      For a more complex example of customizing the user info claims script, see How do I add a session property claim to the OIDC Claims Script in the Knowledge Base.

      You can also use the script to override the claims included in an ID token. For example, you can add a post_logout_url claim that redirects a user’s browser to the URL specified in the claim, when that user signs out of an End User UI.

      The following example adds a final item to claimAttributes to return https://forgerock.com as the post_logout_url claim. Adapt the method used to return the appropriate URL for your application:

      +

      claimAttributes = [
              //...,
              "post_logout_url": { claim, identity -> return [(claim.getName()): "https://forgerock.com"] }
      ]

      Add the claim for the fr:idm:* scope as a final item in the scopeClaimsMap:

      +

      scopeClaimsMap = [
              //...,
              "fr:idm:*": [ "post_logout_url" ]
      ]
  3. Save your changes.

The default user info claims script is now amended to retrieve a custom claim for the profile scope.

Configure AM to use the user info claims script

Perform this task to set up an OAuth2 provider to use your custom 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:

    • OIDC Claims Plugin Type to SCRIPTED.

    • OIDC Script to OIDC Claims Script.

    If you created a new script rather than editing the default, you need to reference the new script name here.

  3. Save your changes.

Create an OAuth2 client for authorization

Create a public 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): openid profile

  3. Click Create.

  4. In the Core tab, set Client type to Public.

  5. In the Advanced tab, set the following values:

    • Grant Types: Implicit

    • Token Endpoint Authentication Method: none

    • Grant Types: token id_token

AM is now prepared for you to try the sample user info claims script.

Try the custom user info claims plugin script

To try your custom script, use the Implicit grant flow as demonstrated in the following steps.

  1. Log in to AM as the demo user, for example:

    $ curl \
    --request POST \
    --header "Content-Type: application/json" \
    --header "X-OpenAM-Username: demo" \
    --header "X-OpenAM-Password: Ch4ng31t" \
    --header "Accept-API-Version: resource=2.0, protocol=1.0" \
    'https://openam.example.com:8443/openam/json/realms/root/realms/alpha/authenticate'
    {
        "tokenId":"AQIC5wM…​TU3OQ*",
        "successUrl":"/openam/console",
        "realm":"/alpha"
    }

    Note the SSO token value returned as tokenId in the output.

  2. Invoke the authorization server’s /oauth2/authorize endpoint specifying the SSO token value in a cookie, and the following parameters as a minimum:

    • client_id=myClient

    • response_type=token id_token

    • scope=openid profile

    • nonce=your nonce value

    • redirect_uri=https://www.example.com:443/callback

    • decision=allow

    • csrf=SSO-token

      For example:

      $ curl --dump-header - \
      --Cookie "iPlanetDirectoryPro=AQIC5wM…​TU3OQ*" \
      --request POST \
      --data "client_id=myClient" \
      --data "response_type=token id_token" \
      --data "scope=openid profile" \
      --data "state=123abc" \
      --data "nonce=abc123" \
      --data "decision=allow" \
      --data "csrf=AQIC5wM…​TU3OQ*" \
      --data "redirect_uri=https://www.example.com:443/callback" \
      "https://openam.example.com:8443/openam/oauth2/realms/root/realms/alpha/authorize"

      If the authorization server successfully authenticates the user, note the value of the access token appended to the redirection URI in the response.

  3. Call the /oauth2/userinfo endpoint to inspect the custom claim values, including the access token obtained from the previous request.

    For example:

    $ curl --request GET --header "Authorization: Bearer az91IvnIQ-uP3Eqw5QqaXXY_DCo" \
    "https://openam.example.com:8443/openam/oauth2/realms/root/realms/alpha/userinfo"
    {
      "given_name":"Demo First Name",
      "family_name":"Demo Last Name",
      "name":"demo",
      "myTestName":"demo",
      "sub":"(usr!demo)",
      "subname":"demo"
    }

    Verify that the response contains the custom claim added by the script (myTestName in this example).

OAuth 2.0 user info claims scripting API

The following properties are available to user info claims scripts, in addition to the common OAuth 2.0 script properties.

Show script properties
claims

Contains a map of the claims the server provides by default. For example:

{
  "sub": "248289761001",
  "updated_at": "1450368765"
}
claimsLocales

The values from the 'claims_locales' parameter. For details, see Claims Languages and Scripts in the OpenID Connect Core 1.0 specification..

claimObjects

The default claims provided by the server. Always present.

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 update the Custom Properties field. The custom properties can be added in the format shown in these examples:

customproperty=custom-value1
customList[0]=customList-value-0
customList[1]=customList-value-1
customMap[key1]=customMap-value-1
customMap[key2]=customMap-value-2

From within the script, you can then access the custom properties in the following way:

var customProperties = clientProperties.get("customProperties");
var property = customProperties.get(<PROPERTY_KEY>);
identity

Contains a representation of the identity of the resource owner.

For more details, see the com.sun.identity.idm.AMIdentity class in the ForgeRock Access Management Javadoc.

requestedClaims

Contains requested claims if the claims query parameter is used in the request, and Enable "claims_parameter_supported" is checked in the OAuth 2.0 provider service configuration; otherwise, this property is empty.

For more information see Requesting Claims using the "claims" Request Parameter in the OpenID Connect Core 1.0 specification.

Example:

{
  "given_name": {
    "essential": true,
    "values": [
      "Demo User",
      "D User"
    ]
  },
  "nickname": null,
  "email": {
    "essential": true
  }
}
requestedTypedClaims

Contains a list of requested claims if the claims query parameter is used in the request, and Enable "claims_parameter_supported" is checked in the OAuth 2.0 provider service configuration. Otherwise, this property is empty.

A claim with a single value indicates this is the only value that should be returned.

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:

[
  "profile",
  "openid"
]
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.

Copyright © 2010-2024 ForgeRock, all rights reserved.