Allow Users to Choose MFA Enrollment Using Auth0 Forms and Actions

Overview

By default, Auth0’s Multi-Factor Authentication (MFA) settings are typically configured to be either always on or never on, without providing users a direct choice. This article outlines a workaround to enable users to decide whether they want to enroll in MFA by leveraging Auth0 Forms and Post-Login Actions.

Applies To

  • Multi-Factor Authentication (MFA)
  • Forms
  • Actions

Solution

Create the Form

  1. Log in to the Auth0 Dashboard.
  2. Navigate to Actions > Forms.
  3. Select Create New Form and choose Start from scratch.
  4. From the Components section, drag a Boolean field into the step.
  5. In the Label field, add text such as “Do you want to enroll with MFA?
  6. Select Save and Publish.

Create a Flow

  1. Select Flows > Create Flow.
  2. After the flow is created, select the plus sign (+).
  3. From the List of actions, choose Update User.
  4. Edit the Update User action.
  5. Choose a vault connection.
  6. In the User ID field, set the value to {{context.user.user_id}}.
  7. In the Body, add the following JSON:
{
  "user_metadata": {
    "mfa": ""
  }
}
  1. For the value of the mfa field, add the boolean input data received from the form. Select the variable selector and set the variable to mfa field from the form.
  2. Select Save and Publish.

Connect the Form to the Flow

  1. Navigate back to Forms.
  2. From the bottom of the screen, select Flow, and then from Flow settings, select the Flow just created.
  3. Add the flow between the “Step” and “Ending screen” elements in the form’s design.
  4. Publish the form.
  5. Select Render and copy the ID of the form. It will be needed later.

Create a Post-Login Action
To create an action:

  1. Navigate to Actions > Triggers > Post Login.
  2. From Add action, click the plus sign (+) and choose Build from scratch.
  3. From the Custom actions, choose the action just created and drag it between “Start” and “Complete.”
  4. Select Apply.

Below is an example of the JavaScript code for a Post-Login Action. This is a starting point which can customize it as needed to fit specific requirements:

exports.onExecutePostLogin = async (event, api) => {
  if(!!event.user?.multifactor === false || (Array.isArray(event.user?.multifactor) && event.user?.multifactor.length === 0)){
  api.prompt.render(event.secrets.form_id);
}}

exports.onContinuePostLogin = async (event, api) => {
  if (event.user.user_metadata && event.user.user_metadata.mfa ){

  api.multifactor.enable('any', {allowRememberBrowser: false});
}}

NOTE: The api.multifactor.enable(‘any’) command will trigger enrollment for any MFA factors you have enabled in an Auth0 tenant.