Post-Login Action to Trigger MFA OTP or Email as Fallback

Overview

A Post-Login Action is needed for new users to enroll in MFA OTP. Once they verify their email address, users are implicitly enrolled in Email MFA. Currently, the MFA OTP enrollment option is not seen for users logging in for the first time, and returning users are only prompted for Email MFA. 

 

This article provides an example of how to write a Post-Login Action that would accommodate both OTP and Email MFA for users. 

Applies To
  • Multi Factor Authentication
  • MFA
Solution
The following Action will check a user's enrolled factors and prompt the user to enroll in enabled MFA factors if they have not enrolled already. Otherwise, users will be prompted with OTP and have the Email factor available as a fallback as well.

NOTE: This is not production-ready code and should always be heavily tested before using it in any production environment.
 
exports.onExecutePostLogin = async (event, api) => {
 
    const enrolledFactors = (event.user.enrolledFactors || []).filter(f => f.type !== 'email').map(f => ({ type: f.type }));

    if (enrolledFactors.length == 0) {
        api.multifactor.enable("any", {allowRememberBrowser: false});
    } else {
        api.authentication.challengeWith(
    {type:'otp'}, {additionalFactors:[{type:'email'}]});
    }

};

Recommended content

No recommended content found...