Example Use Cases - Auth0 Docs

Custom Token Exchange Use Cases

You can use Custom Token Exchange to solve advanced integration scenarios where normal federated login strategies based on redirecting the end user cannot be applied due to technical or user experience constraints. The code provided for the use cases is incomplete and only aims to show the logical steps you can follow with your code to address the use case. Refer to code samples for more detailed code examples.

Auth0 recommends using normal, out-of-the-box federated login whenever possible. By allowing you to set the user for the transaction, Custom Token Exchange gives you more flexibility by taking on the additional responsibility of securely validating and handling the transaction.

Use Cases

This section describes example use cases and specific code samples with recommendations for implementing your scenario. To illustrate the use cases, we will use GearUp, a fictional car rental service company.

Use Case: Seamless migration into Auth0

GearUp has a mobile App used by millions of people and needs to modernize their Identity solution so they’ve decided to switch to Auth0. However, they want to avoid forcing users to re-authenticate as they migrate from their legacy identity provider, or IdP, as that adds friction to the user experience. To solve this, and to limit risks, GearUp is migrating incrementally. For each user, they wish to exchange the refresh token from their legacy IdP for an Auth0 access token, refresh token and ID token set. This allows their app to seamlessly start using Auth0 as the IdP for this user, as well as consume GearUp APIs using Auth0-issued tokens. Once the exchange is done for all users, the app will be fully migrated and the old IdP can be disconnected–all without impacting end users and GearUp’s business.

  1. The mobile app makes a request to Auth0 to exchange the legacy refresh token, setting it as the subject token.
  2. The corresponding Custom Token Exchange profile Action executes. It validates the refresh token with the legacy IdP and gets the external user ID from the user profile. It then applies the required authorization policy and finally sets the user.
  3. Auth0 responds with Auth0 access token, ID token, and refresh token.
  4. The mobile app can now use the Customer APIs using Auth0 tokens without the user having to re-authenticate.

The following code sample shows how to implement this in the Custom Token Exchange Action. In this case, since user profiles were already imported into an Auth0 database connection:

/**
* Handler to be executed while executing a custom token exchange request
* @param {Event} event - Details about the incoming token exchange request.
* @param {CustomTokenExchangeAPI} api - Methods and utilities to define token exchange process.
*/
exports.onExecuteCustomTokenExchange = async (event, api) => {
 // 1. VALIDATE the refresh_token received in the subject_token by using it to get
 // the UserProfile from the external IdP
 const { isValid, user } = await getUserProfile(
 event.transaction.subject_token,
 event.secrets.CLIENT_SECRET,
 );
 if (!isValid) {
 // Mark the subject token as invalid and fail the transaction.
 api.access.rejectInvalidSubjectToken("Invalid subject_token");
 } else {
 // 2. Apply your AUTHORIZATION POLICY as required to determine if the request is valid.
 // Use api.access.deny() to reject the transaction in those cases.
 
 // 3. When we have the profile, we SET THE USER in the target connection
 api.authentication.setUserByConnection(
 connectionName,
 {
 user_id: user.sub,
 },
 {
 creationBehavior: "none",
 updateBehavior: "none",
 },
 );
 }
};

/**
* Exchange the refresh token and load the user profile from the legacy IdP
* @param {string} refreshToken
* @param {string} clientSecret
* @returns {Promise<{ isValid: boolean, user?: object }>} If the refresh token was exchanged successfully, returns the user profile
*/
async function getUserProfile(refreshToken, clientSecret) {
 // Add your code here. REFER TO CODE SAMPLES FOR DETAILED EXAMPLES
}

Use Case: Re-use an external authentication provider

Another use case involves GearUp partnering with Air0, a leading travel provider, to offer their car rental services directly within the Air0 single-page application. GearUp offers a JavaScript library that encapsulates the use of their APIs. This way GearUp’s APIs can easily be consumed by Air0’s website where car rental services are being offered. Once again, the solution needs to be invisible to end users by avoiding re-authentication to GearUp. To solve this problem, GearUp’s JavaScript library can perform a token exchange using the external Air0 ID token as the input. This results in an Auth0 access token that is generated and associated with the corresponding GearUp user based on their email address. Once the GearUp library gets the access token, it can start using GearUp’s APIs to offer car rental services directly within Air0’s website.

  1. The Single Page App gets the ID token from the external IdP once the user authenticates.
  2. It then requests the exchanges of the ID token, setting it as the subject token.
  3. The corresponding Custom Token Exchange profile Action executes. It validates the ID token and gets the user ID and other profile attributes from the token. It then applies the required authorization policy and finally sets the user.
  4. Auth0 responds with Auth0 access token, ID token and refresh token.
  5. The javascript code running in the SPA can now use the Customer APIs using Auth0 tokens without the user having to re-authenticate.

The following code exemplifies how to implement this in the Custom Token Exchange Action. In this case:

const jwksUri = "https://example.com/.well-known/jwks.json";

/**
 * Handler to be executed while executing a custom token exchange request
 * @param {Event} event - Details about the incoming token exchange request.
 * @param {CustomTokenExchangeAPI} api - Methods and utilities to define token exchange process.
 */
exports.onExecuteCustomTokenExchange = async (event, api) => {
  // 1. VALIDATE the id_token received in the subject_token
  const { isValid, payload } = await validateToken(
    event.transaction.subject_token,
  );

if (!isValid) {
    // Mark the subject token as invalid and fail the transaction.
    api.access.rejectInvalidSubjectToken("Invalid subject_token");
  } else {
    // 2. Apply your AUTHORIZATION POLICY as required to determine if the request is valid.
    // Use api.access.deny() to reject the transaction in those cases.

// 3. SET THE USER in the target connection.
    api.authentication.setUserByConnection(
      'Enterprise-OIDC',
      {
          user_id: formattedUserId,
          email: subject_token.email,
          email_verified: subject_token.email_verified,
          phone_number: subject_token.phone_number,
          phone_verified: subject_token.phone_number_verified,
          username: subject_token.preferred_username,
          name: subject_token.name,
          given_name: subject_token.given_name,
          family_name: subject_token.family_name,
          nickname: subject_token.nickname,
          verify_email: false
      },
      {
          creationBehavior: 'create_if_not_exists',
          updateBehavior: 'none'
      }
    );
  }

/**
   * Validate the subject token
   * @param {string} subjectToken
   * @returns {Promise<{ isValid: boolean, payload?: object }>} Payload of the token
   */
  async function validateToken(subjectToken) {
    // Add your code here. REFER TO CODE SAMPLES FOR DETAILED EXAMPLES
  }
};

Use Case: Get Auth0 tokens for another audience

GearUp wants to improve how it authorizes calls between its internal microservices to serve API requests. It wants a centralized policy controlling the resources that each service can consume. This can also be solved using Token Exchange. When the API request first arrives at service A, it exchanges the received access token for a new one that allows it to consume service B as the new audience. If the authorization policy governing the token exchange allows it, service A gets the new token back and can now consume service B. The user ID is kept unchanged in the new token, so the proper user context is retained throughout the process.

  1. The app sends the request with the initial access token to API A.
  2. API A backend service validates the access token and requests to exchange by setting it as the subject token for a new access token to consume API B.
  3. The corresponding Custom Token Exchange profile Action executes. It validates the access token and gets the Auth0 user ID from the token. It then applies the required authorization policy and finally sets the user.
  4. Auth0 responds with an Auth0 access token to consume the API B audience.
  5. API A backend service calls API B using the new access token, which is still associated with the same user.

The following code exemplifies how to implement this in the Custom Token Exchange Action. In this case:

const jwksUri = "https://example.com/.well-known/jwks.json";

/**
 * Handler to be executed while executing a custom token exchange request
 * @param {Event} event - Details about the incoming token exchange request.
 * @param {CustomTokenExchangeAPI} api - Methods and utilities to define token exchange process.
 */
exports.onExecuteCustomTokenExchange = async (event, api) => {
  // 1. VALIDATE the access_token received in the subject_token
  const { isValid, payload } = await validateToken(
    event.transaction.subject_token,
  );

// 3. SET THE USER
    api.authentication.setUserById(payload.sub);
  }

### Use case: Perform MFA during Custom Token Exchange
Building upon the Use Case: Re-use an external authentication provider, GearUp now wants to confirm user presence when a token from the external authentication provider is used. This is necessary to mitigate security risks such as token theft or scenarios where MFA is not supported by the external authenticator. GearUp has two options to achieve this: implement an organization-wide MFA policy or programmatically trigger MFA using a Post Login Action.

First, define the Action, using `api.multifactor.enable()` to trigger an MFA challenge. This function is described in [Post Login API documentation](/content/docs/actions/reference/post-login/post-login-api-object/index.html).

```javascript
exports.onExecutePostLogin = async (event, api) => {
  api.multifactor.enable('any');
};

Use Case: Support agent acting on behalf of an end user via API

GearUp’s support agents need to access end-user data and perform actions via GearUp’s backend APIs on behalf of the end-user. The support tool authenticates the agent, then uses the Custom Token Exchange to obtain an access token representing the end-user with the agent tracked as the actor.

In this case, the agent’s Auth0 ID token is sent as the actor_token in the request, and a signed JWT identifying the end user is sent as the subject_token. When actor_token_type is set to urn:ietf:params:oauth:token-type:id_token, Auth0 automatically validates the token (signature, expiry, issuer) and populates event.transaction.actor_token_user with the agent’s profile. This eliminates the need for custom validation code for the actor token.

  1. The support tool authenticates the agent with Auth0 and obtains the agent’s ID token.
  2. The support tool calls Auth0’s /oauth/token using a Custom Token Exchange request, including a signed JWT with the end-user’s identifier as subject_token and the agent’s ID token as actor_token.
  3. The Custom Token Exchange Action validates the subject token, verifies the actor has the right to act on behalf of the end user, and calls api.authentication.setActor().
  4. Auth0 issues tokens with the act claim identifying the support agent.
  5. The support agent consumes the API on behalf of the end user. APIs can inspect the act claim to apply authorization policies specific to delegated access, such as restricting write operations or logging activity for audit purposes.
const jwksUri = "https://gearup.com/.well-known/jwks.json";

/**
 * Handler to be executed while executing a custom token exchange request
 * @param {Event} event - Details about the incoming token exchange request.
 * @param {CustomTokenExchangeAPI} api - Methods and utilities to define token exchange process.
 */
exports.onExecuteCustomTokenExchange = async (event, api) => {
  // 1. VALIDATE the end-user token received in the subject_token
  const { isValid, payload } = await validateToken(event.transaction.subject_token);

if (!isValid) {
    api.access.rejectInvalidSubjectToken("Invalid subject_token");
    return;
  }

// 2. AUTHORIZE the actor — verify the agent has the right to act on behalf of this end-user
  const actorUser = event.transaction.actor_token_user;
  if (!actorUser) {
    api.access.deny("invalid_request", "Actor token is required for this profile");
    return;
  }

const isAuthorized = await checkDelegationPolicy(actorUser.user_id, payload.sub);
  if (!isAuthorized) {
    api.access.deny("unauthorized_actor", "Agent is not authorized to act on behalf of this user");
    return;
  }

// 3. SET THE ACTOR to include the act claim in issued tokens
  api.authentication.setActor({
    sub: actorUser.user_id,
    sub_profile: "human",
    role: "support"
  });

// 4. SET THE USER for the transaction (the end-user being acted upon)
  api.authentication.setUserById(payload.sub);

async function validateToken(subjectToken) {
    // Add your code here. REFER TO CODE SAMPLES FOR DETAILED EXAMPLES
  }

async function checkDelegationPolicy(agentId, userId) {
    // Implement your delegation policy check here.
    return true;
  }
};

Use Case: Support agent accessing a web application on behalf of an end user

Sometimes a support agent needs to reproduce an issue directly in GearUp’s web application, acting as the end-user, rather than just calling GearUp’s API. Instead of exchanging tokens for an access token, the support tool requests a Session Transfer Token, which it uses to establish a delegated web session for the end-user in GearUp’s web application.

  1. The support tool authenticates the agent with Auth0 and obtains the agent’s ID token.
  2. The support tool calls Auth0’s /oauth/token using a Custom Token Exchange request, setting audience to urn:YOUR_AUTH0_TENANT_DOMAIN:session_transfer, with a signed JWT identifying the end-user as subject_token and the agent’s ID token as actor_token.
  3. The associated Custom Token Exchange Action validates the subject token, authorizes the delegation, and calls api.authentication.setActor() and api.authentication.setUserByConnection() to select the connection the target application accepts.
  4. Auth0 issues a Session Transfer Token instead of an access token.
  5. The support tool redirects the agent’s browser to GearUp’s web application, passing the Session Transfer Token as a query parameter.
  6. GearUp’s web application passes the Session Transfer Token through to its own call to Auth0’s /authorize endpoint, which validates the token and establishes an ephemeral, time-limited session for the end-user, with the agent recorded as the actor for auditing.

Important considerations for delegated authorization

When implementing delegated authorization with Custom Token Exchange, follow these guidelines: