Catch up on everything announced at Firebase Summit, and learn how Firebase can help you accelerate app development and run your app with confidence. Learn More

管理多因素用戶

透過集合功能整理內容 你可以依據偏好儲存及分類內容。

本文檔向您展示瞭如何使用 Firebase Admin SDK 以編程方式管理您的多因素用戶。在管理多因素用戶時,與單因素用戶相比,您可以訪問更多的用戶屬性。

在你開始之前

安裝 Node.js 管理 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('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);
});