Sample Use Cases: Scopes and Claims

Sample Use Cases: Scopes and Claims

In these examples, we use the Authorization Code Flow to authenticate a user and request the necessary permissions (scopes) and tokens. For details on the request parameters or to learn how to fully implement this flow, read our tutorial: Add Login to Regular Web Applications.

Authenticate a user and request standard claims

In this example, we want to authenticate a user and get user details that will allow us to personalize our user interface. To do this, we need to get an ID token that contains the user's name, nickname, profile picture, and email information.

  1. Initiate the authentication flow by sending the user to the authorization URL:

    https://{yourDomain}/authorize?
      response_type=code&
      client_id={yourClientId}&
      redirect_uri={https://yourApp/callback}&
      scope=openid%20profile%20email&
      state=YOUR_STATE_VALUE

    Was this helpful?

    /
    Notice that in this example:

    • The response_type parameter includes one value:

      • code: because we are using the regular web app flow, our initial request is for an authorization code; when we request our tokens using this code, we will receive the ID Token we need for authentication.

    • The scope parameter includes three values; the requested OIDC scopes:

      • openid: to indicate that the application intends to use OIDC to verify the user's identity.

      • profile: to get name, nickname, and picture.

      • email: to get email and email_verified.

  2. After the user consents (if necessary) and Auth0 redirects back to your app, request tokens.

  3. Extract the ID token from the response and decode it. You should see the following claims:

    {
      "name": "John Doe",
      "nickname": "john.doe",
      "picture": "https://myawesomeavatar.com/avatar.png",
      "updated_at": "2017-03-30T15:13:40.474Z",
      "email": "john.doe@test.com",
      "email_verified": false,
      "iss": "https://{yourDomain}/",
      "sub": "auth0|USER-ID",
      "aud": "{yourClientId}",
      "exp": 1490922820,
      "iat": 1490886820,
      "nonce": "crypto-value",
      "at_hash": "IoS3ZGppJKUn3Bta_LgE2A"
    }

    Was this helpful?

    /
    Your app can now retrieve the user attributes and use them to personalize your UI.

Request custom API access

In this example, we request a custom scope for a calendar API that will authorize the calling application to read appointments for the user. To do this, we want to get an access token containing the proper scope to read appointments from the API. Note that requesting an access token is not dependent on requesting an ID token.

Before using a custom API, you need to know what scopes are available for the API you are calling. If the custom API is under your control, you need to register both your application and API with Auth0 and define the scopes for your API using the Auth0 Dashboard. You can also use defined permissions to customize the consent prompt for your users.

  1. Initiate the authorization flow by sending the user to the authorization URL:

    https://{yourDomain}/authorize?
      response_type=code&
      client_id={yourClientId}&
      redirect_uri={https://yourApp/callback}& 
      scope=read:appointments&
      audience=YOUR_API_AUDIENCE&
      state=YOUR_STATE_VALUE

    Was this helpful?

    /
    Notice that in this example:

    • The response_type parameter still includes one value:

      • code: because we are using the regular web app flow, our initial request is for an authorization code; when we request our tokens using this code, we will receive the Access Token that we can use to call our API.

    • the scope parameter includes one value; the requested API scope:

      • read:appointments: to allow us to read the user's appointments from the API.

    • The audience parameter is new and includes one value:

      • The unique identifier of the API from which we want to read the user's appointments.

  2. As in the previous example, after the user consents (if necessary) and Auth0 redirects back to your app, request tokens.

  3. Extract the access token from the response, and call the API using the access token as credentials.

Authenticate a user and request standard claims and custom API access

In this example, we combine our previous two examples to authenticate a user, request standard claims, and also request a custom scope for a calendar API that will allow the calling application to read appointments for the user. To do this, get two tokens:

  • ID token that contains:

    • User name

    • Nickname

    • Profile picture

    • Email information

  • Access token that contains the proper scope to read appointments from the API. Note that requesting an access token is not dependent on requesting an ID token.

Before using a custom API, you need to know what scopes are available for the API you are calling. If the custom API is under your control, you need to register both your application and API with Auth0 and define the scopes for your API using the Auth0 Dashboard. You can also use defined permissions to customize the consent prompt for your users.

  1. Initiate the authentication flow by sending the user to the authorization URL:

    https://{yourDomain}/authorize?
      response_type=code&
      client_id={yourClientId}&
      redirect_uri={https://yourApp/callback}& 
      scope=openid%20profile%20email%20read:appointments&
      audience=YOUR_API_AUDIENCE&
      state=YOUR_STATE_VALUE

    Was this helpful?

    /
    Notice that in this example:

    • The response_type parameter still includes one value:

      • code: because we are using the regular web app flow, our initial request is for an authorization code; when we request our tokens using this code, we will receive both the ID token we need for authentication and the access token that we can use to call our API.

    • The scope parameter is used for both OIDC scopes and API scopes, so now includes four values:

      • openid: to indicate that the application intends to use OIDC to verify the user's identity.

      • profile: to get name, nickname, and picture.

      • email: to get email and email_verified.

      • read:appointments: to allow us to read the user's appointments from the API.

    • the audience parameter includes one value:

      • The unique identifier of the API from which we want to read the user's appointments

  2. As in the previous examples, after the user consents (if necessary) and Auth0 redirects back to your app, request tokens.

  3. Extract the ID token from the response, decode it, and retrieve the user attributes and use them to personalize your UI.

  4. Extract the access token from the response, and call the API using the access token as credentials.

Add custom claims to a token

In this example, we add a user's favorite color and preferred contact method to the ID Token. To do this, we create an Action to customize the ID token by adding these claims. Once added, we will also be able to obtain the custom claims when calling the /userinfo endpoint (though the Action will run only during the authentication process).

Suppose that:

  • At some point, the user selected a preferred_contact method of email and a favorite_color of red, and we saved it as part of the user's user_metadata.

  • We've used the Management API or the Dashboard to set application-specific information for this user.

In this case, the Auth0-stored normalized user profile is:

{
  "email": "jane@example.com",
  "email_verified": true,
  "user_id": "custom|123",
  "favorite_color": "blue",
  "user_metadata": {
    "preferred_contact": "email"
  }
}

Was this helpful?

/

For this profile, Auth0 would normally return the following ID Token claims to your application:

{
  "email": "jane@example.com",
  "email_verified": true,
  "iss": "https://my-domain.auth0.com/",
  "sub": "custom|123",
  "aud": "my_client_id",
  "iat": 1311280970,
  "exp": 1311281970
}

Was this helpful?

/

Notice that in this example:

  • The sub claim contains the value of the user_id property.

  • Neither the favorite_color nor user_metadata properties are present because OpenID Connect (OIDC) does not define standard claims that represent favorite_color or user_metadata.

To receive the custom data, we'll need to create a new Action to customize the token with a custom claims that represent these properties from the user profile.

  1. Navigate to Auth0 Dashboard > Actions > Library, and select Build Custom.

  2. Enter a descriptive Name for your Action (for example, Add user metadata to tokens), select the Login / Post Login trigger because you’ll be adding the Action to the Login flow, then select Create.

  3. Locate the Actions Code Editor, copy the following JavaScript code into it, and select Save Draft to save your changes:

    exports.onExecutePostLogin = async (event, api) => {
      const namespace = 'https://myapp.example.com';
      const { favorite_color, preferred_contact } = event.user.user_metadata;
    
      if (event.authorization) {
        // Set claims 
        api.idToken.setCustomClaim(`${namespace}/favorite_color`, favorite_color);
        api.idToken.setCustomClaim(`${namespace}/preferred_contact`, preferred_contact);
      }
    };

    Was this helpful?

    /

  4. From the Actions Code Editor sidebar, select Test (play icon), then select Run to test your code.

  5. When you’re ready for the Action to go live, select Deploy.

Finally, add the Action you created to the Login Flow. To learn how to attach Actions to Flows, read the "Attach the Action to a flow" section in Write Your First Action.

With this Action enabled, Auth0 will include the favorite_color and preferred_contact custom claims in the ID Token:

{
  "email": "jane@example.com",
  "email_verified": true,
  "iss": "https://my-domain.auth0.com/",
  "sub": "custom|123",
  "aud": "my_client_id",
  "iat": 1311280970,
  "exp": 1311281970,
  "https://myapp.example.com/favorite_color": "red",
  "https://myapp.example.com/preferred_contact": "email"
}

Was this helpful?

/

When creating your Action, make sure to set some logic that determines when to include additional claims. Injecting custom claims into every ID Token that is issued is not ideal.

This example shows custom claims being added to an ID Token, which uses the api.idToken.setCustomClaims method. To add these claims to an Access Token, use the api.accessToken.setCustomClaim method.

To learn more about the event object for the trigger, read Actions Triggers: post-login - Event Object. To learn more about tokens, read Tokens.

Learn more