管理多重驗證使用者

本文件說明如何使用 Firebase Admin SDK 透過程式管理多重驗證使用者。與單一因素使用者相比,管理多重驗證使用者時,您可以存取更多範圍的使用者屬性。

事前準備

安裝 Node.js Admin SDK。目前不支援其他 Admin SDK 語言。

取得使用者

您可以從 UserRecord 物件擷取使用者的多重要素相關資料,例如已註冊的第二因素清單。如要取得使用者記錄,請呼叫 getUser()getUserByEmail()

以下範例顯示已註冊多重驗證的使用者:

// console.log(userRecord.toJSON());
{
  uid: 'some-uid',
  displayName: 'John Doe',
  email: 'johndoe@gmail.com',
  photoURL: 'http://www.example.com/12345678/photo.png',
  emailVerified: true,
  phoneNumber: '+11234567890',
  // Set this user as admin.
  customClaims: {admin: true},
  // User with Google provider.
  providerData: [{
    uid: 'google-uid',
    email: 'johndoe@gmail.com',
    displayName: 'John Doe',
    photoURL: 'http://www.example.com/12345678/photo.png',
    providerId: 'google.com'
  }],
  multiFactor: {
    enrolledFactors: [
      // 2FA with SMS as 2nd factor.
      {
        uid: '53HG4HG45HG8G04GJ40J4G3J',
        phoneNumber: '+16505551234',
        displayName: 'Work phone',
        enrollmentTime: 'Fri, 22 Sep 2017 01:49:58 GMT',
        factorId: 'phone',
      },
    ],
  },
};

列出使用者

以下程式碼說明如何列出所有使用者,並檢查他們是否已註冊次要因素:

admin.auth().listUsers(1000, nextPageToken)
  .then((listUsersResult) => {
    listUsersResult.users.forEach((userRecord) => {
      // Multi-factor enrolled users second factors can be retrieved via:
      if (userRecord.multiFactor) {
        userRecord.multiFactor.enrolledFactors.forEach((enrolledFactor) => {
          console.log(userRecord.uid, enrolledFactor.toJSON());
        });
      }
    });
  })
  .catch((error) => {
    console.log('Error listing users:', error);
  });

系統會以批次傳回使用者,並依照 uid 排序。每個結果批次都包含使用者清單,以及用於擷取下一批次的下一頁權杖。列出所有使用者後,系統不會傳回 pageToken

maxResult 欄位會指定批次大小上限。預設值和最大值為 1000。

建立使用者

呼叫 createUser() 即可建立新使用者。使用次要因素的新使用者必須擁有已驗證的電子郵件地址 (將 emailVerified 設為 true),並使用支援的第一個因素登入。每位使用者最多可設定 5 個次要驗證因素。

以下範例說明如何使用 2 個次要因素建立新使用者:

admin.auth().createUser({
  uid: '123456789',
  email: 'user@example.com',
  emailVerified: true,
  password: 'password',
  multiFactor: {
    enrolledFactors: [
      // When creating users with phone second factors, the uid and
      // enrollmentTime should not be specified. These will be provisioned by
      // the Auth server.
      // Primary second factor.
      {
        phoneNumber: '+16505550001',
        displayName: 'Corp phone',
        factorId: 'phone',
      },
      // Backup second factor.
      {
        phoneNumber: '+16505550002',
        displayName: 'Personal phone',
        factorId: 'phone'
      },
    ],
  },
})
.then((userRecord) => {
  console.log(userRecord.multiFactor.enrolledFactors);
})
.catch((error) => {
  console.log(error);
});

更新使用者

如要更新現有使用者,請呼叫 updateUser()

admin.auth().updateUser(uid: '123456789', {
  multiFactor: {
    enrolledFactors: [
      {
        // uid will be auto-generated.
        phoneNumber: '+16505550003',
        displayName: 'Spouse\'s phone',
        factorId: 'phone',
      },
      {
        // uid can also be specified. This is useful if a new second factor is added and an
        // existing enrolled second factor is kept unmodified.
        uid: 'existing-enrolled-mfa-uid',
        phoneNumber: '+16505550004',
        displayName: 'Personal phone',
        factorId: 'phone',
      },
      {
        phoneNumber: '+16505550005',
        displayName: 'Backup phone',
        factorId: 'phone',
        // Enrollment time can also be explicitly specified.
        enrollmentTime: new Date().toUTCString(),
      },
    ],
  },
})
.then((userRecord) => {
  console.log(userRecord.multiFactor.enrolledFactors);
})
.catch((error) => {
  console.log(error);
});

新增次要因素

使用 enrolledFactors 清單呼叫 updateUser() 會清除使用者目前的所有次要因素。如要新增次要因素並保留現有因素,請先查詢使用者,然後將新因素新增至清單:

function enrollSecondFactor(userId, secondFactorPhoneNumber, secondFactorDisplayName) {
  return admin.auth().getUser(userId)
    .then((userRecord) => {
      const updatedList = (userRecord.multiFactor &&
        userRecord.multiFactor.toJSON().enrolledFactors) || [];
      updatedList.push({
        phoneNumber: secondFactorPhoneNumber,
        displayName: secondFactorDisplayName,
        factorId: 'phone',
      });
      return admin.auth().updateUser(userRecord.uid, {
        multiFactor: {
          enrolledFactors: updatedList,
        },
      });
    })
    .catch((error) => {
      console.log(error);
    });
}

移除次要驗證方式

如要完全取消使用者註冊多重驗證,請將 enrolledFactors 設為 null 或空陣列:

admin.auth().updateUser(uid: '123456789', {
  multiFactor: {
    enrolledFactors: null,
  },
})
.then((userRecord) => {
  console.log(userRecord.multiFactor);
})
.catch((error) => {
  console.log(error);
});