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

管理用户

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

Firebase Admin SDK 提供了一个 API,用于管理具有更高权限的 Firebase 身份验证用户。管理员用户管理 API 使您能够从安全的服务器环境中以编程方式完成以下任务:

  • 在没有任何节流或速率限制的情况下创建新用户。
  • 通过不同的标准查找用户,例如 uid、电子邮件或电话号码。
  • 批量列出指定项目的所有用户。
  • 访问用户元数据,包括帐户创建日期和上次登录日期。
  • 删除用户而不需要他们的现有密码。
  • 更新用户属性 - 包括他们的密码 - 无需以用户身份登录。
  • 无需通过用于验证电子邮件的带外操作流程即可验证电子邮件。
  • 在不发送电子邮件链接的情况下更改用户的电子邮件以撤销这些更改。
  • 使用电话号码创建新用户,无需通过短信验证流程。
  • 无需通过短信验证流程即可更改用户的电话号码。
  • 离线提供处于禁用状态的用户,然后控制何时启用它们。
  • 构建针对特定应用程序的用户管理系统量身定制的自定义用户控制台。

在你开始之前

要使用 Firebase Admin SDK 提供的用户管理 API,您必须拥有服务帐号。按照设置说明获取有关如何初始化 Admin SDK 的更多信息。

检索用户数据

识别用户的主要方法是通过他们的uid ,该用户的唯一标识符。 Admin SDK 提供了一种方法,允许通过用户的uid获取用户的个人资料信息:

节点.js

getAuth()
  .getUser(uid)
  .then((userRecord) => {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log(`Successfully fetched user data: ${userRecord.toJSON()}`);
  })
  .catch((error) => {
    console.log('Error fetching user data:', error);
  });

爪哇

UserRecord userRecord = FirebaseAuth.getInstance().getUser(uid);
// See the UserRecord reference doc for the contents of userRecord.
System.out.println("Successfully fetched user data: " + userRecord.getUid());

Python

from firebase_admin import auth

user = auth.get_user(uid)
print('Successfully fetched user data: {0}'.format(user.uid))

// Get an auth client from the firebase.App
client, err := app.Auth(ctx)
if err != nil {
	log.Fatalf("error getting Auth client: %v\n", err)
}

u, err := client.GetUser(ctx, uid)
if err != nil {
	log.Fatalf("error getting user %s: %v\n", uid, err)
}
log.Printf("Successfully fetched user data: %v\n", u)

C#

UserRecord userRecord = await FirebaseAuth.DefaultInstance.GetUserAsync(uid);
// See the UserRecord reference doc for the contents of userRecord.
Console.WriteLine($"Successfully fetched user data: {userRecord.Uid}");

此方法返回与提供给该方法的uid对应的用户的UserRecord对象。

如果提供的uid不属于现有用户或由于任何其他原因无法获取用户,则上述方法会抛出错误。有关错误代码的完整列表,包括描述和解决步骤,请参阅Admin Auth API Errors

在某些情况下,您将获得用户的电子邮件而不是他们的uid 。 Firebase Admin SDK 支持通过邮箱查找用户信息:

节点.js

getAuth()
  .getUserByEmail(email)
  .then((userRecord) => {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log(`Successfully fetched user data: ${userRecord.toJSON()}`);
  })
  .catch((error) => {
    console.log('Error fetching user data:', error);
  });

爪哇

UserRecord userRecord = FirebaseAuth.getInstance().getUserByEmail(email);
// See the UserRecord reference doc for the contents of userRecord.
System.out.println("Successfully fetched user data: " + userRecord.getEmail());

Python

from firebase_admin import auth

user = auth.get_user_by_email(email)
print('Successfully fetched user data: {0}'.format(user.uid))

u, err := client.GetUserByEmail(ctx, email)
if err != nil {
	log.Fatalf("error getting user by email %s: %v\n", email, err)
}
log.Printf("Successfully fetched user data: %v\n", u)

C#

UserRecord userRecord = await FirebaseAuth.DefaultInstance.GetUserByEmailAsync(email);
// See the UserRecord reference doc for the contents of userRecord.
Console.WriteLine($"Successfully fetched user data: {userRecord.Uid}");

此方法为与提供的电子邮件对应的用户返回一个UserRecord对象。

如果提供的电子邮件不属于现有用户或由于任何其他原因无法获取用户,Admin SDK 会抛出错误。有关错误代码的完整列表,包括描述和解决步骤,请参阅管理员身份验证 API 错误

在其他情况下,您将拥有用户的电话号码而不是他们的uid 。 Firebase Admin SDK 支持通过电话号码查找用户信息:

节点.js

getAuth()
  .getUserByPhoneNumber(phoneNumber)
  .then((userRecord) => {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log(`Successfully fetched user data:  ${userRecord.toJSON()}`);
  })
  .catch((error) => {
    console.log('Error fetching user data:', error);
  });

爪哇

UserRecord userRecord = FirebaseAuth.getInstance().getUserByPhoneNumber(phoneNumber);
// See the UserRecord reference doc for the contents of userRecord.
System.out.println("Successfully fetched user data: " + userRecord.getPhoneNumber());

Python

from firebase_admin import auth

user = auth.get_user_by_phone_number(phone)
print('Successfully fetched user data: {0}'.format(user.uid))

u, err := client.GetUserByPhoneNumber(ctx, phone)
if err != nil {
	log.Fatalf("error getting user by phone %s: %v\n", phone, err)
}
log.Printf("Successfully fetched user data: %v\n", u)

C#

UserRecord userRecord = await FirebaseAuth.DefaultInstance.GetUserByPhoneNumberAsync(phoneNumber);
// See the UserRecord reference doc for the contents of userRecord.
Console.WriteLine($"Successfully fetched user data: {userRecord.Uid}");

此方法返回与提供的电话号码对应的用户的UserRecord对象。

如果提供的电话号码不属于现有用户或由于任何其他原因无法获取用户,Admin SDK 会抛出错误。有关错误代码的完整列表,包括描述和解决步骤,请参阅管理员身份验证 API 错误

批量检索用户数据

Firebase Admin SDK 还允许根据您提供的标识符检索用户列表。您可以通过用户 ID、电子邮件或电话号码来识别用户。一次调用最多可提供 100 个标识符。标识符可以包含多种类型:

节点.js

getAuth()
  .getUsers([
    { uid: 'uid1' },
    { email: 'user2@example.com' },
    { phoneNumber: '+15555550003' },
    { providerId: 'google.com', providerUid: 'google_uid4' },
  ])
  .then((getUsersResult) => {
    console.log('Successfully fetched user data:');
    getUsersResult.users.forEach((userRecord) => {
      console.log(userRecord);
    });

    console.log('Unable to find users corresponding to these identifiers:');
    getUsersResult.notFound.forEach((userIdentifier) => {
      console.log(userIdentifier);
    });
  })
  .catch((error) => {
    console.log('Error fetching user data:', error);
  });

爪哇

GetUsersResult result = FirebaseAuth.getInstance().getUsersAsync(Arrays.asList(
    new UidIdentifier("uid1"),
    new EmailIdentifier("user2@example.com"),
    new PhoneIdentifier("+15555550003"),
    new ProviderIdentifier("google.com", "google_uid4"))).get();

System.out.println("Successfully fetched user data:");
for (UserRecord user : result.getUsers()) {
  System.out.println(user.getUid());
}

System.out.println("Unable to find users corresponding to these identifiers:");
for (UserIdentifier uid : result.getNotFound()) {
  System.out.println(uid);
}

Python

from firebase_admin import auth

result = auth.get_users([
    auth.UidIdentifier('uid1'),
    auth.EmailIdentifier('user2@example.com'),
    auth.PhoneIdentifier(+15555550003),
    auth.ProviderIdentifier('google.com', 'google_uid4')
])

print('Successfully fetched user data:')
for user in result.users:
    print(user.uid)

print('Unable to find users corresponding to these identifiers:')
for uid in result.not_found:
    print(uid)

getUsersResult, err := client.GetUsers(ctx, []auth.UserIdentifier{
	auth.UIDIdentifier{UID: "uid1"},
	auth.EmailIdentifier{Email: "user@example.com"},
	auth.PhoneIdentifier{PhoneNumber: "+15555551234"},
	auth.ProviderIdentifier{ProviderID: "google.com", ProviderUID: "google_uid1"},
})
if err != nil {
	log.Fatalf("error retriving multiple users: %v\n", err)
}

log.Printf("Successfully fetched user data:")
for _, u := range getUsersResult.Users {
	log.Printf("%v", u)
}

log.Printf("Unable to find users corresponding to these identifiers:")
for _, id := range getUsersResult.NotFound {
	log.Printf("%v", id)
}

C#

GetUsersResult result = await FirebaseAuth.DefaultInstance.GetUsersAsync(
    new List<UserIdentifier>
    {
        new UidIdentifier("uid1"),
        new EmailIdentifier("user2@example.com"),
        new PhoneIdentifier("+15555550003"),
        new ProviderIdentifier("google.com", "google_uid4"),
    });

Console.WriteLine("Successfully fetched user data:");
foreach (UserRecord user in result.Users)
{
    Console.WriteLine($"User: {user.Uid}");
}

Console.WriteLine("Unable to find users corresponding to these identifiers:");
foreach (UserIdentifier uid in result.NotFound)
{
    Console.WriteLine($"{uid}");
}

此方法返回一个与输入列表大小相同的列表,其中每个条目包含相应的UserRecord或指示无法查找该标识符的原因的错误。有关错误代码的完整列表,包括描述和解决步骤,请参阅管理员身份验证 API 错误

创建用户

Admin SDK 提供了一种允许您创建新的 Firebase 身份验证用户的方法。此方法接受一个对象,该对象包含要包含在新创建的用户帐户中的配置文件信息:

节点.js

getAuth()
  .createUser({
    email: 'user@example.com',
    emailVerified: false,
    phoneNumber: '+11234567890',
    password: 'secretPassword',
    displayName: 'John Doe',
    photoURL: 'http://www.example.com/12345678/photo.png',
    disabled: false,
  })
  .then((userRecord) => {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully created new user:', userRecord.uid);
  })
  .catch((error) => {
    console.log('Error creating new user:', error);
  });

爪哇

CreateRequest request = new CreateRequest()
    .setEmail("user@example.com")
    .setEmailVerified(false)
    .setPassword("secretPassword")
    .setPhoneNumber("+11234567890")
    .setDisplayName("John Doe")
    .setPhotoUrl("http://www.example.com/12345678/photo.png")
    .setDisabled(false);

UserRecord userRecord = FirebaseAuth.getInstance().createUser(request);
System.out.println("Successfully created new user: " + userRecord.getUid());

Python

user = auth.create_user(
    email='user@example.com',
    email_verified=False,
    phone_number='+15555550100',
    password='secretPassword',
    display_name='John Doe',
    photo_url='http://www.example.com/12345678/photo.png',
    disabled=False)
print('Sucessfully created new user: {0}'.format(user.uid))

params := (&auth.UserToCreate{}).
	Email("user@example.com").
	EmailVerified(false).
	PhoneNumber("+15555550100").
	Password("secretPassword").
	DisplayName("John Doe").
	PhotoURL("http://www.example.com/12345678/photo.png").
	Disabled(false)
u, err := client.CreateUser(ctx, params)
if err != nil {
	log.Fatalf("error creating user: %v\n", err)
}
log.Printf("Successfully created user: %v\n", u)

C#

UserRecordArgs args = new UserRecordArgs()
{
    Email = "user@example.com",
    EmailVerified = false,
    PhoneNumber = "+11234567890",
    Password = "secretPassword",
    DisplayName = "John Doe",
    PhotoUrl = "http://www.example.com/12345678/photo.png",
    Disabled = false,
};
UserRecord userRecord = await FirebaseAuth.DefaultInstance.CreateUserAsync(args);
// See the UserRecord reference doc for the contents of userRecord.
Console.WriteLine($"Successfully created new user: {userRecord.Uid}");

默认情况下,Firebase 身份验证将为新用户生成一个随机uid 。如果您想为新用户指定自己的uid ,则可以将其作为参数传递给用户创建方法:

节点.js

getAuth()
  .createUser({
    uid: 'some-uid',
    email: 'user@example.com',
    phoneNumber: '+11234567890',
  })
  .then((userRecord) => {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully created new user:', userRecord.uid);
  })
  .catch((error) => {
    console.log('Error creating new user:', error);
  });

爪哇

CreateRequest request = new CreateRequest()
    .setUid("some-uid")
    .setEmail("user@example.com")
    .setPhoneNumber("+11234567890");

UserRecord userRecord = FirebaseAuth.getInstance().createUser(request);
System.out.println("Successfully created new user: " + userRecord.getUid());

Python

user = auth.create_user(
    uid='some-uid', email='user@example.com', phone_number='+15555550100')
print('Sucessfully created new user: {0}'.format(user.uid))

params := (&auth.UserToCreate{}).
	UID(uid).
	Email("user@example.com").
	PhoneNumber("+15555550100")
u, err := client.CreateUser(ctx, params)
if err != nil {
	log.Fatalf("error creating user: %v\n", err)
}
log.Printf("Successfully created user: %v\n", u)

C#

UserRecordArgs args = new UserRecordArgs()
{
    Uid = "some-uid",
    Email = "user@example.com",
    PhoneNumber = "+11234567890",
};
UserRecord userRecord = await FirebaseAuth.DefaultInstance.CreateUserAsync(args);
// See the UserRecord reference doc for the contents of userRecord.
Console.WriteLine($"Successfully created new user: {userRecord.Uid}");

可以提供以下属性的任意组合:

表 1. 创建用户操作支持的属性

财产类型描述
uid细绳分配给新创建的用户的uid 。必须是长度介于 1-128 个字符(含)之间的字符串。如果未提供,将自动生成随机uid 。较短的uid提供更好的性能。
email细绳用户的主要电子邮件。必须是一个有效的E-mail地址。
emailVerified布尔值用户的主要电子邮件是否经过验证。如果未提供,则默认为false
phoneNumber细绳用户的主要电话号码。必须是符合 E.164 规范的有效电话号码。
password细绳用户的未经哈希处理的原始密码。长度必须至少为六个字符。
displayName细绳用户的显示名称。
photoURL细绳用户的照片 URL。
disabled布尔值用户是否被禁用。 true残疾人来说是正确的; false启用。如果未提供,则默认为false

用户创建方法为新创建的用户返回一个UserRecord对象。

如果提供的uid 、电子邮件或电话号码已被现有用户使用,或者由于任何其他原因无法创建用户,则上述方法将失败并出现错误。有关错误代码的完整列表,包括描述和解决步骤,请参阅管理员身份验证 API 错误

更新一个用户

Firebase Admin SDK 有助于修改现有用户的数据。您需要指定一个uid以及要为该用户更新的属性:

节点.js

getAuth()
  .updateUser(uid, {
    email: 'modifiedUser@example.com',
    phoneNumber: '+11234567890',
    emailVerified: true,
    password: 'newPassword',
    displayName: 'Jane Doe',
    photoURL: 'http://www.example.com/12345678/photo.png',
    disabled: true,
  })
  .then((userRecord) => {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully updated user', userRecord.toJSON());
  })
  .catch((error) => {
    console.log('Error updating user:', error);
  });

爪哇

UpdateRequest request = new UpdateRequest(uid)
    .setEmail("user@example.com")
    .setPhoneNumber("+11234567890")
    .setEmailVerified(true)
    .setPassword("newPassword")
    .setDisplayName("Jane Doe")
    .setPhotoUrl("http://www.example.com/12345678/photo.png")
    .setDisabled(true);

UserRecord userRecord = FirebaseAuth.getInstance().updateUser(request);
System.out.println("Successfully updated user: " + userRecord.getUid());

Python

user = auth.update_user(
    uid,
    email='user@example.com',
    phone_number='+15555550100',
    email_verified=True,
    password='newPassword',
    display_name='John Doe',
    photo_url='http://www.example.com/12345678/photo.png',
    disabled=True)
print('Sucessfully updated user: {0}'.format(user.uid))

params := (&auth.UserToUpdate{}).
	Email("user@example.com").
	EmailVerified(true).
	PhoneNumber("+15555550100").
	Password("newPassword").
	DisplayName("John Doe").
	PhotoURL("http://www.example.com/12345678/photo.png").
	Disabled(true)
u, err := client.UpdateUser(ctx, uid, params)
if err != nil {
	log.Fatalf("error updating user: %v\n", err)
}
log.Printf("Successfully updated user: %v\n", u)

C#

UserRecordArgs args = new UserRecordArgs()
{
    Uid = uid,
    Email = "modifiedUser@example.com",
    PhoneNumber = "+11234567890",
    EmailVerified = true,
    Password = "newPassword",
    DisplayName = "Jane Doe",
    PhotoUrl = "http://www.example.com/12345678/photo.png",
    Disabled = true,
};
UserRecord userRecord = await FirebaseAuth.DefaultInstance.UpdateUserAsync(args);
// See the UserRecord reference doc for the contents of userRecord.
Console.WriteLine($"Successfully updated user: {userRecord.Uid}");

可以提供以下属性的任意组合:

表 2. 更新用户操作支持的属性

财产类型描述
email细绳用户的新主电子邮件。必须是一个有效的E-mail地址。
emailVerified布尔值用户的主要电子邮件是否经过验证。如果未提供,则默认为false
phoneNumber细绳用户的新主电话号码。必须是符合 E.164 规范的有效电话号码。设置为null以清除用户的现有电话号码。
password细绳用户新的未经哈希处理的原始密码。长度必须至少为六个字符。
displayName字符串 | null用户的新显示名称。设置为null以清除用户的现有显示名称。
photoURL字符串 | null用户的新照片 URL。设置为null以清除用户现有的照片 URL。如果非null ,则必须是有效的 URL。
disabled布尔值用户是否被禁用。 true残疾人来说是正确的; false启用。

当更新成功完成时,update user 方法返回一个更新的UserRecord对象。

如果提供的uid不对应于现有用户,提供的电子邮件或电话号码已被现有用户使用,或者由于任何其他原因无法更新用户,则上述方法失败并出现错误。有关错误代码的完整列表,包括描述和解决步骤,请参阅管理员身份验证 API 错误

删除用户

Firebase Admin SDK 允许通过uid删除现有用户:

节点.js

getAuth()
  .deleteUser(uid)
  .then(() => {
    console.log('Successfully deleted user');
  })
  .catch((error) => {
    console.log('Error deleting user:', error);
  });

爪哇

FirebaseAuth.getInstance().deleteUser(uid);
System.out.println("Successfully deleted user.");

Python

auth.delete_user(uid)
print('Successfully deleted user')

err := client.DeleteUser(ctx, uid)
if err != nil {
	log.Fatalf("error deleting user: %v\n", err)
}
log.Printf("Successfully deleted user: %s\n", uid)

C#

await FirebaseAuth.DefaultInstance.DeleteUserAsync(uid);
Console.WriteLine("Successfully deleted user.");

当删除成功完成时,删除用户方法返回空结果。

如果提供的uid不对应于现有用户或由于任何其他原因无法删除用户,删除用户方法会抛出错误。有关错误代码的完整列表,包括描述和解决步骤,请参阅管理员身份验证 API 错误

删除多个用户

Firebase Admin SDK 还可以一次删除多个用户。但是,请注意,使用deleteUsers(uids)等方法一次删除多个用户不会触发 Cloud Functions for Firebase 的onDelete()事件处理程序。这是因为批量删除不会触发每个用户的用户删除事件。如果您希望为每个已删除的用户触发用户删除事件,则一次删除一个用户。

节点.js

getAuth()
  .deleteUsers([uid1, uid2, uid3])
  .then((deleteUsersResult) => {
    console.log(`Successfully deleted ${deleteUsersResult.successCount} users`);
    console.log(`Failed to delete ${deleteUsersResult.failureCount} users`);
    deleteUsersResult.errors.forEach((err) => {
      console.log(err.error.toJSON());
    });
  })
  .catch((error) => {
    console.log('Error deleting users:', error);
  });

爪哇

DeleteUsersResult result = FirebaseAuth.getInstance().deleteUsersAsync(
    Arrays.asList("uid1", "uid2", "uid3")).get();

System.out.println("Successfully deleted " + result.getSuccessCount() + " users");
System.out.println("Failed to delete " + result.getFailureCount() + " users");
for (ErrorInfo error : result.getErrors()) {
  System.out.println("error #" + error.getIndex() + ", reason: " + error.getReason());
}

Python

from firebase_admin import auth

result = auth.delete_users(["uid1", "uid2", "uid3"])

print('Successfully deleted {0} users'.format(result.success_count))
print('Failed to delete {0} users'.format(result.failure_count))
for err in result.errors:
    print('error #{0}, reason: {1}'.format(result.index, result.reason))

deleteUsersResult, err := client.DeleteUsers(ctx, []string{"uid1", "uid2", "uid3"})
if err != nil {
	log.Fatalf("error deleting users: %v\n", err)
}

log.Printf("Successfully deleted %d users", deleteUsersResult.SuccessCount)
log.Printf("Failed to delete %d users", deleteUsersResult.FailureCount)
for _, err := range deleteUsersResult.Errors {
	log.Printf("%v", err)
}

C#

DeleteUsersResult result = await FirebaseAuth.DefaultInstance.DeleteUsersAsync(new List<string>
    {
        "uid1",
        "uid2",
        "uid3",
    });

Console.WriteLine($"Successfully deleted {result.SuccessCount} users.");
Console.WriteLine($"Failed to delete {result.FailureCount} users.");

foreach (ErrorInfo err in result.Errors)
{
    Console.WriteLine($"Error #{err.Index}, reason: {err.Reason}");
}

删除用户方法返回无法删除的用户的失败列表。有关错误代码的完整列表,包括描述和解决步骤,请参阅管理员身份验证 API 错误

列出所有用户

Firebase Admin SDK 允许批量检索整个用户列表:

节点.js

const listAllUsers = (nextPageToken) => {
  // List batch of users, 1000 at a time.
  getAuth()
    .listUsers(1000, nextPageToken)
    .then((listUsersResult) => {
      listUsersResult.users.forEach((userRecord) => {
        console.log('user', userRecord.toJSON());
      });
      if (listUsersResult.pageToken) {
        // List next batch of users.
        listAllUsers(listUsersResult.pageToken);
      }
    })
    .catch((error) => {
      console.log('Error listing users:', error);
    });
};
// Start listing users from the beginning, 1000 at a time.
listAllUsers();

爪哇

// Start listing users from the beginning, 1000 at a time.
ListUsersPage page = FirebaseAuth.getInstance().listUsers(null);
while (page != null) {
  for (ExportedUserRecord user : page.getValues()) {
    System.out.println("User: " + user.getUid());
  }
  page = page.getNextPage();
}

// Iterate through all users. This will still retrieve users in batches,
// buffering no more than 1000 users in memory at a time.
page = FirebaseAuth.getInstance().listUsers(null);
for (ExportedUserRecord user : page.iterateAll()) {
  System.out.println("User: " + user.getUid());
}

Python

# Start listing users from the beginning, 1000 at a time.
page = auth.list_users()
while page:
    for user in page.users:
        print('User: ' + user.uid)
    # Get next batch of users.
    page = page.get_next_page()

# Iterate through all users. This will still retrieve users in batches,
# buffering no more than 1000 users in memory at a time.
for user in auth.list_users().iterate_all():
    print('User: ' + user.uid)

// Note, behind the scenes, the Users() iterator will retrive 1000 Users at a time through the API
iter := client.Users(ctx, "")
for {
	user, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		log.Fatalf("error listing users: %s\n", err)
	}
	log.Printf("read user user: %v\n", user)
}

// Iterating by pages 100 users at a time.
// Note that using both the Next() function on an iterator and the NextPage()
// on a Pager wrapping that same iterator will result in an error.
pager := iterator.NewPager(client.Users(ctx, ""), 100, "")
for {
	var users []*auth.ExportedUserRecord
	nextPageToken, err := pager.NextPage(&users)
	if err != nil {
		log.Fatalf("paging error %v\n", err)
	}
	for _, u := range users {
		log.Printf("read user user: %v\n", u)
	}
	if nextPageToken == "" {
		break
	}
}

C#

// Start listing users from the beginning, 1000 at a time.
var pagedEnumerable = FirebaseAuth.DefaultInstance.ListUsersAsync(null);
var responses = pagedEnumerable.AsRawResponses().GetAsyncEnumerator();
while (await responses.MoveNextAsync())
{
    ExportedUserRecords response = responses.Current;
    foreach (ExportedUserRecord user in response.Users)
    {
        Console.WriteLine($"User: {user.Uid}");
    }
}

// Iterate through all users. This will still retrieve users in batches,
// buffering no more than 1000 users in memory at a time.
var enumerator = FirebaseAuth.DefaultInstance.ListUsersAsync(null).GetAsyncEnumerator();
while (await enumerator.MoveNextAsync())
{
    ExportedUserRecord user = enumerator.Current;
    Console.WriteLine($"User: {user.Uid}");
}

每批结果包含一个用户列表和用于列出下一批用户的下一页令牌。当所有用户都已列出时,不返回pageToken

如果未指定maxResults字段,则使用默认的每批 1000 个用户。这也是一次允许列出的最大用户数。任何大于最大值的值都会引发参数错误。如果未指定pageToken ,该操作将从头开始列出用户,按uid排序。

有关错误代码的完整列表,包括描述和解决步骤,请参阅管理员身份验证 API 错误

列出的用户的密码哈希

如果用于生成请求 OAuth 访问令牌的用户/服务帐户具有firebaseauth.configs.getHashConfig权限,则此 API 还会为密码用户返回由 Firebase Auth 后端散列的passwordSaltpasswordHash 。否则将不会设置passwordHashpasswordSalt

由于密码哈希的敏感性,Firebase Admin SDK 服务帐户默认没有firebaseauth.configs.getHashConfig权限。您不能直接向用户/服务帐户添加权限,但您可以通过创建自定义 IAM 角色间接这样做。

要创建自定义 IAM 角色:

  1. 转到 Google Cloud Console 中IAM 和管理面板中的角色页面。
  2. 从页面顶部的下拉列表中选择您的项目。
  3. 点击创建角色
  4. 单击添加权限
  5. 搜索firebaseauth.configs.getHashConfig权限并选中该复选框。
  6. 点击添加
  7. 单击CREATE完成新角色的创建。

在 IAM 页面中将创建的自定义角色添加到用户/服务帐户:

  1. IAM 和管理面板中,选择IAM
  2. 从成员列表中选择服务或用户帐户进行编辑。
  3. 单击添加另一个角色
  4. 搜索之前创建的新自定义角色。
  5. 点击保存