Fetching Auth0 Metadata

Fetching Auth0 Metadata

Besides the basic user details Auth0 provides (name, email, picture etc), Auth0 allows for additional customizable metadata to be provided for each user.

Auth0 allows two types of metadata to be saved in its database:

Users & Roles > Users > User

Screen Shot 2021-01-09 at 8.32.23 PM.png

**Remember to only use user_metadata if you intend to grant the user read/write access. Otherwise, use app_metadata which will only grant read-only access. **

Are we done? Not quite.

You may soon find out that accessing these metadata in your application is a little bit tricky.

Even after you configure user_metadata or app_metadata, your Auth0 request will not yet return the metadata keys.

// using useAuth0 React hook to extract user details. 
const {user} = useAuth0()
console.log(user)

Screen Shot 2021-01-09 at 6.49.08 PM.png

I'll save you several painful hours of head scratching and searching the internet for solutions (resources are hard to find).

Let's proceed to the additional steps needed to access both user_metadata and app_metadata in your application.

First go to **Rules > Create Rule. **

Screen Shot 2021-01-09 at 4.30.42 PM.png

Since I'll be providing you the code, just click on create Empty rule.

Let's create a rule to access hobby in user_metadata .

function (user, context, callback) {
 // provide a url namespace string
  const namespace = 'https://www.test-namespace.com/';
  context.idToken[namespace + 'user_metadata_hobby'] =user.user_metadata.hobby;
  callback(null, user, context);
}

To further nail the concept in, let's create another rule to access hardcore_coder in app_metadata.

function (user, context, callback) {
  // provide a url namespace string
  const namespace = 'https://www.test-namespace.com/';
  context.idToken[namespace + 'app_metadata_hardcore_coder'] =user.app_metadata.hardcore_coder;
  callback(null, user, context);
}

Reminder: You have to provide a URL namespace string or Auth0 wouldn't return the metadata (I myself got stuck here). This has something to do with OIDC Namespace specifications.

Upon saving, you will see that the metadata are returned in your next Auth0 request.

Screen Shot 2021-01-09 at 6.49.36 PM.png

The application is now able to determine whether a user is a hardcore coder based on Auth0 metadata. haha.

Until next time. Keep learning.

Stay stoked and code. :)


I hope you can voluntarily Buy Me A Coffee if you found this article useful and give additional support for me to continue sharing more content for the community. :)

Thank you very much. :)