How to Get Country Code and Phone Number During MFA Enrollment

Problem Statement:

How to get the country code and phone number during MFA enrollment.

Solution:

Here are the steps and sample scripts:

1.Disable the phone number obfuscation by sending the following body to the /api/v2/tenants/settings endpoint:

{
"flags":{
             "disable_management_api_sms_obfuscation":true
            }
}

If true, SMS phone numbers will not be obfuscated in Management API GET calls.

2.Write a rule to call /api/v2/guardian/enrollments/{id} endpoint and retrieve MFA enrolled settings each time and save it in the user app_metadata.

Here is the sample code:

function usernameAttribute(user, context, callback) {
       user.app_metadata = user.app_metadata || {};
       // short-circuit if the user has MFA records in the metadata already
       if (user.app_metadata.phoneNumber) return callback(null, user, context);
       var ManagementClient = require('auth0@2.19.0').ManagementClient;
       var management = new ManagementClient({
              token: auth0.accessToken,
              domain: auth0.domain
        });
        let phoneNumber = '';
        management.getGuardianEnrollments({ id: user.user_id }, function (err, enrollments) {
        phoneNumber = enrollments[0].phone_number;
        user.app_metadata.phoneNumber = phoneNumber;
        auth0.users.updateAppMetadata(user.user_id, user.app_metadata).then(function () {
                 callback(null, user, context); 
         }).catch(function (err) {
             callback(err);
        });
   });
}

That would give you a result like this after OTP via SMS was done:

{
     id: ‘sms|dev_1234567890’,
     status: ‘confirmed’,
     enrolled_at: ‘2022-03-08T14:17:36.000Z’,
     last_auth: ‘2022-03-08T14:17:36.000Z’,
     type: ‘sms’,
     auth_method: ‘sms’,
     phone_number: ‘+44 1234567890’
}

3.You can make a GET request to /api/v2/users/{id} endpoint to get user.app_metadata.phoneNumber which includes both the country code and the number.

Reference:

1 Like