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
- Log in to the Auth0 Dashboard.
- Navigate to Actions > Forms.
- Select Create New Form and choose Start from scratch.
- From the Components section, drag a Boolean field into the step.
- In the Label field, add text such as “Do you want to enroll with MFA?”
- Select Save and Publish.
Create a Flow
- Select Flows > Create Flow.
- After the flow is created, select the plus sign (+).
- From the List of actions, choose Update User.
- Edit the Update User action.
- Choose a vault connection.
- In the User ID field, set the value to
{{context.user.user_id}}
. - In the Body, add the following JSON:
{
"user_metadata": {
"mfa": ""
}
}
- 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.
- Select Save and Publish.
Connect the Form to the Flow
- Navigate back to Forms.
- From the bottom of the screen, select Flow, and then from Flow settings, select the Flow just created.
- Add the flow between the “Step” and “Ending screen” elements in the form’s design.
- Publish the form.
- Select Render and copy the ID of the form. It will be needed later.
Create a Post-Login Action
To create an action:
- Navigate to Actions > Triggers > Post Login.
- From Add action, click the plus sign (+) and choose Build from scratch.
- From the Custom actions, choose the action just created and drag it between “Start” and “Complete.”
- 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.