Enrich User Profiles

Published on August 23, 2022
Learning GoalLearn how to enrich user profiles using Auth0 Actions.

In this lab, you will:

  • Create, integrate, and update a Post-Login Auth0 Action.
  • Enrich a user profile with geolocation data at login.
  • Inspect an ID token to verify user profile information.

What Is Profile Enrichment?

You may need more user information to carry out business operations than what your users can provide immediately during the sign-up or login process. How should you get that information? Asking for repetitive information every time a user logs in will hurt the user experience. Additionally, nobody in your organization should manually look up pieces of information to add to every user profile either.

You can augment user profile information from your own data sources. You can also obtain a great deal of user information from external services. This practice is known as profile enrichment: you automatically grab information, which may be publicly available, and add it to a user's profile. An easy way to enrich user profiles is by using Auth0 Actions.

Profile enrichment in action

Actions are functions that execute at certain points during the Auth0 runtime, such as when a user signs up or logs in. For profile enrichment, your Action could call an API to grab some data and then put any relevant information into the profile that every user gets when they sign up through Auth0. You could also integrate that data with the profile of existing users who are logging in but are missing that information.

For simplicity, this lab will integrate location data provided by the Auth0 Authorization API with the user profile. After completing this lab, you should be in good shape to integrate any external or internal API with your Auth0 login flow using Actions.

Lab Setup

Create an Auth0 Account

If you already have an Auth0 account, you can log in to your tenant and continue to the next step.

Otherwise, sign up for a free Auth0 account.

During the sign-up process, you create something called an Auth0 Tenant, representing the product or service to which you are adding authentication.

Once you sign in, Auth0 takes you to the Auth0 Dashboard, where you can configure and manage the authentication services for your applications.

Create a Post-Login Action

It would be best for you to use a non-production tenant where you are comfortable trying new features.

You can add Actions to a Flow from the Auth0 Marketplace as seen in the "Country-Based Access" Actions lab. You can also build them with custom code to extend the default Auth0 behavior. Let's do that!

Ensure that you are still logged in to the Auth0 Dashboard and follow these steps:

  • Head to the Auth0 Dashboard.
  • Click the "Actions" tab on the left-hand menu.
  • Click the "Flows" option.
Flows are a set of Actions that Auth0 executes in sequence whenever any of the various triggers are invoked in the Auth0 pipeline (such as a user logging in).
  • Click on the "Login" flow.
  • Locate the "Add Action" panel on the right-hand side and click the "+" button.
  • Click the "Build Custom" option from the flyout menu.
  • The "Create Action" modal comes up with a form that you need to fill out as follows:
  • Click the "Create" button to complete this process.

Build a custom Action with Node.js

The Actions Code Editor loads up, where you need to replace the uncommented code,

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

with the following code:

ACTION
exports.onExecutePostLogin = async (event, api) => {
const cityName = event.request.geoip.cityName;
const countryName = event.request.geoip.countryName;
const timeZone = event.request.geoip.timeZone;
api.user.setUserMetadata("city", cityName);
api.user.setUserMetadata("country", countryName);
api.user.setUserMetadata("timezone", timeZone);
};

In the Post-Login Action code above, the event object for the post-login Actions trigger provides contextual information about a single user who is logging in via Auth0.

The event.request property is an object with details about the request that initiated the login transaction. These details include the geoip object, which in turn includes the cityName, countryName, and timeZone values.

You can then use the api object to access helper methods that can modify artifacts of the login transaction such as user profile information, ID tokens, and access tokens.

In this case, you access the api.user to make application-specific changes to the metadata associated with the user logging in, the user_metadata object.

What can developers do with Auth0 metadata?

Auth0 provides a comprehensive system for storing metadata in the Auth0 user profile. You can use metadata to store three types of information:

  • User information: Stores user attributes such as preferences that do not impact a user's core functionality. This information shows up under the user_metadata section of a user profile in the Auth0 Dashboard.
  • Access information: Stores information such as permissions, Auth0 plan, and external IDs that can impact user access to features. This information shows up under the app_metadata section of a user profile in the Auth0 Dashboard.
  • Application information: Stores information about an application, which OpenID Connect (OIDC) and OAuth 2.0 refer to as the client. This information is present in the event.client.metadata object of a Post-Login Action.

In your Post-Login Action, you use the api.user.setUserMetadata() method to set location metadata for the user logging in. After a user logs in, that location information will show up in the user_metadata section of the user profile in the Auth0 Dashboard as follows:

{
"city": "cityName",
"country": "countryName",
"timezone": "timeZone"
}

You'll test that out shortly. For now, click the "Save Draft" button to save your changes, and then click the "Deploy" button.

Integrate a Post-Login Action

Follow these steps to integrate the Post-Login Action with your Login Flow:

  • Head to the Login Flow panel by clicking the "Back to flow" button on the top-left corner.
  • Click the "Custom" tab under the "Add Action" panel.
  • Drag and drop the "Profile Enrichment" block between the "Start" and "Complete" event icons on the Flow board, which is located to the left.
If you completed the "Country-Based Access Control" Action lab, place the "Profile Enrichment" block after the "Country-Based Access Control" one. Auth0 should only save user metadata if the authentication pipeline is successful, which will happen if only if you log in from an allowed country.
  • Click the "Apply" button to make this Login pipeline effective.
You will get a toast notification with the following message: "Login flow updated".

Test the Profile Enrichment

Use the Auth0 Dashboard to log in

Instructions

  • Visit the Auth0 Dashboard home page.
  • Locate the "Try your Login box" under the "Next Steps" section.
  • Click the "Try it out" link.
  • Log in using any of the available login options.

Expected results

Verify that the location data is, in fact, in the user metadata by following these steps:

  • Head to the Auth0 Dashboard.
  • Click the "User Management" tab on the left-hand menu and then select the "Users" option.
  • In the list of users that comes up, click the name of the user you used to log in. The Auth0 user profile page will load up.
  • Under the "Details" tab, locate the "Metadata" section. Then, within that section, locate the user_metadata sub-section.
  • Verify that the user_metadata matches the following structure:
{
"city": "cityName",
"country": "countryName",
"timezone": "timeZone"
}

The accuracy of the location information from where you logged in will depend on your device's privacy settings and whether or not you are using a VPN,

In your applications, you can build a form using the Management API that will allow your users to edit that user metadata to provide the correct values if needed. But if the information were correct, your users would not need to spend any time filling out forms.

Update a Post-Login Action

After every successful login, Auth0 sends an ID token to your application with user profile information. You can update your Post-Login Action to add custom data to that ID token. Doing so will allow you to share the location information present in the scope of your Post-Login Action with your client application.

Follow these steps to access the Post-Login Action that you've created:

  • Head to the Auth0 Dashboard.
  • Click the "Actions" tab on the left-hand menu and then select the "Library" option.
    • The page that loads up helps you manage your actions and configuration.
  • Click the "Custom" tab.
  • Select your "Profile Enrichment" Post-Login Action.

Update your Action code as follows:

ACTION
exports.onExecutePostLogin = async (event, api) => {
const cityName = event.request.geoip.cityName;
const countryName = event.request.geoip.countryName;
const timeZone = event.request.geoip.timeZone;
api.user.setUserMetadata("city", cityName);
api.user.setUserMetadata("country", countryName);
api.user.setUserMetadata("timezone", timeZone);
if (event.authorization) {
const namespace = "https://example.com";
api.idToken.setCustomClaim(`${namespace}/location`, {
cityName,
countryName,
timeZone,
});
}
};

What's new on this Action?

  • The event.authorization object contains information describing the authorization granted to the user logging in.
  • You verify that the event.authorization object is defined as that represents a successful login transaction.
    • You won't have access to the ID token if the user cannot log in.
  • Auth0 recommends using a namespace whenever you need to add custom data to an ID token. In this case, you use https://example.com as the namespace value.
    • Auth0 recommends using a fully-qualified URL as the value of a namespace.
    • Read the "Create Custom Claims" document for more details and recommendations on enriching the data of tokens.
  • The api.idToken object has methods that help you request changes to the ID token that Auth0 is issuing to the client application that initiated the login transaction.
  • You use the api.idToken.setCustomClaim() method to set a custom claim on that ID token.
    • This method takes two arguments: name, the key for the custom claim, and value, the value of the custom claim.
  • You set the value of your ${namespace}/location custom claim as a JSON object with all the location data.

Now that you have updated your Post-Login Action code click the "Deploy" button to apply this change to your login flow.

Tip: Clicking the "Deploy" button automatically triggers the Auth0 Dashboard to save your Action draft first before deploying it.

Test the ID Token Storage

Use the Auth0 Dashboard to log in

Instructions

  • Visit the Auth0 Dashboard home page.
  • Locate the "Try your Login box" under the "Next Steps" section.
  • Click the "Try it out" link.
  • Log in using any of the available login options.
  • Auth0 redirects you to a callback page, /tester/callback, where you see a box with the user information present in your decoded ID token.

Expected results

Verify that the location data is present in the decoded ID token:

{
"https://example.com/location": {
"cityName": "YOUR-CURRENT-CITY",
"countryName": "YOUR-CURRENT-COUNTRY",
"timeZone": "YOUR-CURRENT-TIMEZONE"
},
// Other claims...
}

The location values in the https://example.com/location custom claim must match 100% of the location values on the user_metadata of your Auth0 user profile. You can verify that if you'd like.

Recap

You have seen in practice how to use Auth0 Actions to integrate data not provided directly by users with their profiles. As a next step, you can try fetching external data from your Post-Login Action. You can use axios to make requests within your Auth0 Action as seen in this example.

Explore progressive profiling

You can also use Actions to implement progressive profiling in your applications. Progressive profiling is the process of gathering additional user information over time as your users engage with your application. You can gather detailed user information only when relevant to a user's activities. Progressive profiling speeds up the sign-up process by asking fewer questions upfront, leading to higher conversion rates.

For example: When users sign up using a social connection such as Google, you get their name, verified email address, and other basic information from their Google profile. However, you could ask your users for their job title and company name the next time they log in.

Profile enrichment and progressive profiling help you avoid asking users for the information you may already have.