Customize Claims for OpenID Connect

Drupal, out of the box, cannot provide all the data suggested in the OpenID Connect Standard Claims. This means that in order to implement the different claims sites will need to let Simple OAuth know about those implementation details.

In order to add or alter custom claims to the OpenID Connect (aka OIDC) there are two steps necessary:

  • Implement hook_simple_oauth_oidc_claims_alter to alter the associative array containing the claims and their values.
  • Add the claim names to the services.yml listing all the claims available on the responses. Any modules helpfully implementing this hook in their code will need to be whitelisted, so the site is always aware of what claims are being exposed.

Example: Adding the phone_number claim

You can download the code for the simple_oauth_companion module from here. Bear in mind that you will still need to edit your services.yml file.

This example assumes that you have added a phone field to the user entity field_phone_number. It also assumes that you created a custom module simple_oauth_companion to hold the custom code.

Step 1: simple_oauth_companion.module

 * Implements hook_simple_oauth_oidc_claims_alter().
function simple_oauth_companion_simple_oauth_oidc_claims_alter(array &$claim_values, array &$context) {
  $account = $context['account'];
  assert($account instanceof UserInterface);
  $value = $account->get('field_phone_number')->getValue();
  $claim_values['phone_number'] = $value[0]['value'] ?? NULL;

Step 2: web/sites/default/services.yml

# ... append at the end.
    - sub
    - name
    - preferred_username
    - email
    - email_verified
    - locale
    - profile
    - updated_at
    - zoneinfo
    - phone_number # <-- This is the new claim.

Final result

If all went well the OIDC claims will now contain the additional phone_number claim, like below. Check the /oauth/userinfo endpoint to see if the data is available.

  "sub": "36",
  "name": "test",
  "preferred_username": "test",
  "email": "",
  "email_verified": true,
  "profile": "http:\/\/\/en\/user\/36",
  "locale": "en",
  "zoneinfo": "Europe\/Madrid",
  "updated_at": "1601238333",
  "phone_number": "+1 985 43 99 01"

Photo by Kevin Jesus Horacio on Unsplash

👋 Subscribe!

If you like this content, you might consider subscribing to this site's RSS feed. This is the best way to stay up to date with new content on the site. If you don't know how to subscribe, you can check this tutorial.

Load Comments