Custom Claims added to accessToken not being returned from /userinfo

Hello! I’m trying to follow the directions here to add custom claims to access tokens:

I’ve created an action that looks like this and added it to the login flow, and seems to work fine when I run it in the editor:

exports.onExecutePostLogin = async (event, api) => {
  api.accessToken.setCustomClaim('https://redacted/app_metadata', event.user.app_metadata);
};

However, when I call the /userinfo endpoint with a logged in user’s access token, like so:

const resp = await fetch('https://redacted.auth0.com/userinfo', {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${session?.accessToken}`,
      },
    });

The response contains user info but not the app_metadata I tried to add via the action above.

Is there a step I’m missing? Or a better approach to accessing the app_metadata for a user? For context, I’m trying to access it in the getServerSideProps of a nextjs application.

Hi @alexandra1,

Welcome to the Auth0 Community!

I understand that you have added custom claims to an access token but were not able to see them in the token.

After looking closely at the code snippet you shared, I noticed that you are calling the /userinfo endpoint with the token you obtained from the login flow. In this situation, the audience parameter was never passed in the login request which results in opaque access tokens.

These tokens do not contain custom claims.

To get the custom claims, you must specify an API identifier in the login request as your audience query parameter.

For example:

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

After the login flow is complete, the access token returned can be decoded in jwt.io to see the custom claims.

I hope the explanation was clear! Here are some helpful resources worth checking out:

Please reach out if you have questions or need further clarification.

Thanks,
Rueben

I see, thanks for the speedy reply! From the docs it seems like the audience would be for an api we’ve built but that the audience for userinfo always results in an opaque token.

If we don’t have a custom api I’m trying to access and I just want to access the app_metadata for a user, is it better to add it to the idToken since that’s already in JWT format (i.e. once we have the token we can access it without any additional api calls)?

Hi @alexandra1

Thank you for your response.

Yes, that is correct. You could workaround this by appending the custom claims to the ID Token rather than the access token.

As a reminder, you must include the openid scope in the login request to get an ID Token.

May I help you with anything else?

Thanks,
Rueben

1 Like

Nope that should work for me! Thanks so much!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.