OpenID Connect Reconcile Lambda

On this page

When an OpenID Connect identity provider is used to complete a federated login request, FusionAuth will use the configured linking strategy and well known OpenID Connect claims to reconcile the user. FusionAuth will attempt to match the user information returned from the OpenID Connect identity provider to an existing user account or create a new one.

You may optionally utilize a lambda to customize the user and user registration during the authentication event.

The UserInfo response from an OpenID Connect identity provider often includes custom claims. To copy custom claims to fields on the FusionAuth user, use a lambda.

When you create a new lambda using the FusionAuth Admin UI, you will be provided an empty function to implement.

Starting in version 1.65.0, you can use attribute mappings to map IdP claims directly to FusionAuth user and registration fields without writing a lambda. Reconcile lambdas and attribute mappings are mutually exclusive. Attempting to configure both on a given IdP results in a validation error.

Lambda Structure#

When you create the lambda with the API, give the function the following signature:

function reconcile(user, registration, jwt, id_token, tokens, context) {
  // Lambda code goes here
}

This lambda must contain a function named reconcile that accepts the following parameters:

  • user: the FusionAuth User object. You can modify this object. However, you can't change the email or username attributes after FusionAuth links the user.
  • registration: the FusionAuth UserRegistration object. You can modify this object.
  • jwt: the JSON payload returned from the OpenID Connect UserInfo endpoint. This object is read-only. For a full list of standard claims, see the UserInfo Response reference.
  • id_token: the JSON payload returned in the id_token, or null when the id_token is not available. This object is read-only. For a full list of standard claims, see the ID Token reference.  Available since 1.31.0
  • tokens: an object containing the encoded versions of the access_token and optionally the id_token when available. This object is read-only.  Available since 1.48.0
  • context: an object containing the context of the request, including access to secrets. This object is read-only.  Available since 1.64.0

The User API and Registration API documentation describe the user and registration objects.

The jwt object holds the payload from the UserInfo endpoint. The payload can include registered OpenID Connect claims and custom claims from the Identity Provider.

FusionAuth passes the id_token to the lambda only when the IdP returns an id_token with a valid signature. The IdP returns an id_token when you request the openid scope.

FusionAuth verifies the signature in one of two ways:

  • The IdP signs the token with the client_secret and an HMACA way to sign a message with a shared secret and a hash function, such as SHA-256. FusionAuth uses HMAC to sign JSON Web Tokens and webhooks. algorithm.
  • The IdP signs the token with an asymmetric key pair. The IdP publishes the public key in a JSON Web Key SetA JSON object that contains a set of JSON Web Keys. FusionAuth publishes the public keys that verify JSON Web Tokens as a JSON Web Key Set. (JWKS), and the jwks_uri in the .well-known/openid-configuration discovery document points to the JWKS. For FusionAuth to find the public key, configure the IdP with the Issuer so FusionAuth can read the discovery document. If you configure the Authorize, Token, and UserInfo endpoints by hand, FusionAuth doesn't discover the JWKS URI.

Before version 1.48.0, FusionAuth passed the id_token only when the IdP signed the token with the client_secret and an HMAC algorithm.

The tokens object always holds the encoded access_token. When FusionAuth verifies the id_token signature, the tokens object also holds the encoded id_token. Use these tokens to call an external API with Lambda HTTP Connect.

Assigning The Lambda#

After you create the lambda, assign the lambda to one or more OpenID Connect identity providers.

Navigate to Settings -> Identity Providers . Select your existing OpenID Connect configuration. If you haven't configured OpenID Connect yet, click Add provider and select OpenID Connect.

Example Lambda#

The following lambda reconciles a user after a GitHub login. The lambda copies the GitHub avatar and name to the user, and sets the registration username to the GitHub login. The lambda stores the company and location in user.data, and removes the @ that GitHub adds to organization names in the company field.

The lambda also calls the GitHub API with the access token from the tokens argument to list the user's GitHub organizations. The lambda maps each organization to a role with orgRoles, and drops organizations with no mapping. The call needs the read:org scope in the identity provider configuration. When the call fails, the lambda logs the error and keeps the current roles, so the login still succeeds. Calling an API from a lambda requires the Essentials plan or higher. See Lambda HTTP Connect.

A lambda that saves the GitHub profile and assigns roles from GitHub organizations.
// fills in the profile from GitHub and assigns roles based on the user's GitHub organizations
function reconcile(user, registration, jwt, id_token, tokens, context) {
  user.imageUrl = jwt.avatar_url || user.imageUrl;
  user.fullName = jwt.name || user.fullName;
  registration.username = jwt.login;

  user.data = user.data || {};
  if (jwt.company) {
    // github prefixes organization names with @
    user.data.company = jwt.company.replace(/^@/, '');
  }
  if (jwt.location) {
    user.data.location = jwt.location;
  }

  // requires the read:org scope
  var response = fetch('https://api.github.com/user/orgs', {
    method: 'GET',
    headers: {
      'Accept': 'application/vnd.github+json',
      'Authorization': 'Bearer ' + tokens.access_token
    }
  });

  // keep the current roles instead of failing the login
  if (response.status !== 200) {
    console.error('Could not read GitHub organizations. GitHub returned status ' + response.status + '.');
    return;
  }

  var orgRoles = { 'piedpiper': 'employee', 'piedpiper-admins': 'admin' };
  registration.roles = JSON.parse(response.body)
    .map(function (org) {
      return orgRoles[org.login];
    })
    .filter(Boolean);
}

To see what your IdP returns in the jwt object while you develop a lambda, print the object to the Event Log. Add the following line to the lambda:

console.info(JSON.stringify(jwt, null, 2));

Modifying Email And Username Claims#

The linking strategy decides which value FusionAuth requires to link a user. A strategy that links by email requires an email, and a strategy that links by username requires a username. FusionAuth reads each value from the UserInfo response first, then from the id_token when FusionAuth can verify the id_token signature. When neither has an email claim, the lambda can create a unique value. The email claim is email by default, and the username claim is preferred_username. To change the claim names, set oauth2.emailClaim and oauth2.usernameClaim with the OpenID Connect Identity Provider API.

Note

Available in FusionAuth 1.31.0 and later, and in versions 1.17.3 through 1.28.0.

The following lambda checks the jwt and the id_token for an email address. When neither object has one, the lambda builds an address from the unique sub claim.

A lambda that creates an email address when the identity provider sends none.
// creates an email address from the sub claim when the identity provider sends no email
function reconcile(user, registration, jwt, id_token, tokens, context) {
  var email = jwt.email || (id_token && id_token.email);
  if (!email) {
    // use a domain you control
    user.email = jwt.sub + '@no-email-present.example.com';
  }
}

Use an email domain you control, so an attacker can't receive mail for the address. When the identity provider sends an email_verified claim of false, FusionAuth rejects a link by email, even when the lambda sets the email.

FusionAuth applies lambda changes to the email and username only at the first login, before a link exists. When the lambda changes the value that the linking strategy uses, and the new value matches an existing user, FusionAuth runs the lambda a second time with that user. After FusionAuth links the user, FusionAuth discards lambda changes to the email, the username, and the phone number.

When the linking strategy uses the username, FusionAuth ignores changes to the email. When the linking strategy uses the email, FusionAuth ignores changes to the username. FusionAuth ignores changes to the phone number for both strategies. Changes to the other claim could cause collisions if you change the linking strategy later.