获取我们在 Firebase 峰会上发布的所有信息,了解 Firebase 可如何帮助您加快应用开发速度并满怀信心地运行应用。了解详情

管理多因素用户

本文档向您展示了如何使用 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);
});