How to decode and access custom claims from idToken using react-native-auth0 SDK

Hi community,

I need a bit of assistance…
I am trying to decode the idToken returned from auth0.webAuth.authorize() using the rect-native-auth0 SDK as I have included some custom claims via a Login Action Flow (external user ID and token for 3rd party API).

This is the function that I am calling in my React Native app to log the user in:

export function Auth0Login() {
    auth0.webAuth
      .authorize({
        scope: "openid email"
      })
      .then(res => {
        console.log('authorise reponse: ' + JSON.stringify(res));
        storeTokens({ token: res.accessToken })
      .catch(error => console.log(JSON.stringify(error)));
};

What I would like to do is decode the idToken after authorising, the store the custom claims externalId and externalToken alongside the users Auth0 token using my storeTokens() function (react-native-encrypted-storage library).

I am a bit of a coding novice so please go easy on me :slight_smile:

This is my Login Action for reference, makePostRequestAsync() calls my API with event.user data, creates a user if one doesn’t exist and returns drftid and drfttoken to be added to login claims plus stored in Auth0 app_metadata:

exports.onExecutePostLogin = async (event, api) => {

    await makePostRequestAsync(event.user)
        .then(function (res) {
            api.idToken.setCustomClaim('drftid', res.drftid);
            api.idToken.setCustomClaim('drfttoken', res.drfttoken);
            api.user.setAppMetadata('drftid', res.drftid);
            api.user.setAppMetadata('drfttoken', res.drfttoken);
            console.log('Request: ' + JSON.stringify(event.user) + '.Response: ' + JSON.stringify(res));
        });

};

Hi @jw-85,

Welcome to the Auth0 Community!

I understand you have some questions about decoding your ID Token and Post-Login Action.

First, to validate your ID tokens, you have the option to use one of the JWT.io libraries to parse and inspect them.

As for your Post-Login Action, I noticed that it still needs a namespace to append your custom claims. In this case, you will need to create a namespaced custom claim, which can be any non-Auth0 HTTP or HTTPS URL as the namespace identifier.

However, be mindful that Auth0 domains cannot be used as a namespace identifier, which includes

See below.

exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://my-app.example.com';
  if (event.authorization) {
    await makePostRequestAsync(event.user)
        .then(function (res) {
            api.idToken.setCustomClaim(`${namespace}/drftid`, res.drftid);
            api.idToken.setCustomClaim(`${namespace}/drfttoken`, res.drfttoken);
            api.user.setAppMetadata('drftid', res.drftid);
            api.user.setAppMetadata('drfttoken', res.drfttoken);
            console.log('Request: ' + JSON.stringify(event.user) + '.Response: ' + JSON.stringify(res));
        });
  }
};

Once this is complete, you can decode your custom claims in the ID token.

Please let me know if you have any questions.

Thanks.

Thank you @rueben.tiow I will give that a go in my React Native project now, is there any benefit to using one JWT.io libraries over another? I found jwt-decode - npm (npmjs.com) which looks like its pretty easy to use!

In the mean time though I quickly took a look at my React web project and noticed that const { user } = useAuth0(); object from the auth0/auth0-react SDK returns the claims successfully… don’t suppose you could save me a lot of Googling and help me extract them from the object - the namespace is not playing nicely when trying to set a const?

{"https://drft.io/id":"e2987fb1-a3d9-4ef2-95e2-ea9f78bc54c6","https://drft.io/token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiZTI5ODdmYjEtYTNkOS00ZWYyLTk1ZTItZWE5Zjc4YmM1NGM2In0.C1WjoDJN8Vh_tjoSJCiH8MQovWqhBp-3zjtXSyXO5u8","nickname":"jon","name":"jxxx@xxx.com","picture":"https://s.gravatar.com/avatar/1d148d017bsc7d872184cdfsd7d59eb9ebee?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fjo.png","updated_at":"2022-01-11T20:16:13.732Z","email":"jxxx@xxx.com","email_verified":false,"sub":"auth0|61dd49a63e9c1c7s9006986bf00"}

1 Like

I worked it out (woohoo) :nerd_face:

user["https://drft.io/id"]

1 Like

Hi @jw-85,

Thank you for your response.

Not really, you’re encouraged to use any middleware or one of the existing open-source third-party libraries to parse and validate JWTs.

To get the ID token claims using the useAuth0() hook, you will need to use the getIdTokenClaims method to get the custom claims using the Post-Login Action, as you mentioned earlier. See Auth0ContextInterface | @auth0/auth0-react.

I’m glad everything works now!

Please let me know if there’s anything else I can do to help.

Thank you.

I have just tried that jwt-decode package in my React Native app and I can successfully access the custom id and token claims there too now - thank you for all of your help!

Next on my list is to try and replicate the React isAuthenticated and isLoading states that comes with auth0-react useAuthO hook in React Native so if a person force closes an app and opens it again they aren’t sent back to the logged out page - as far as I am aware, the react-native-auth0 SDK does not have these… is that right @rueben.tiow?

1 Like

Hi @jw-85,

Thank you for the updates and I’m glad you were successfully able to decode the token in your app!

That is correct. The react-native-auth0 SDK only performs the authorization code flow with PKCE.

As mentioned in this issue, it is generally recommended and best practice to keep the user’s access token stored securely and use it while it’s valid (unexpired/unrevoked) to determine if the user’s session is active. If it becomes invalid, you have the option of renewing the session by requesting a new access token using a previously obtained refresh token.

I hope this answers your questions and concerns.

Thanks.