Join us in person and online for Firebase Summit on October 18, 2022. Learn how Firebase can help you accelerate app development, release your app with confidence, and scale with ease. Register now

管理用戶

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

Firebase Admin SDK 提供了一個 API,用於管理具有提升權限的 Firebase 身份驗證用戶。管理員用戶管理 API 使您能夠以編程方式從安全的服務器環境中完成以下任務:

  • 創建沒有任何限製或速率限制的新用戶。
  • 通過不同的標準(如 uid、電子郵件或電話號碼)查找用戶。
  • 批量列出指定項目的所有用戶。
  • 訪問用戶元數據,包括帳戶創建日期和上次登錄日期。
  • 無需用戶現有密碼即可刪除用戶。
  • 無需以用戶身份登錄即可更新用戶屬性(包括其密碼)。
  • 驗證電子郵件,而無需通過帶外操作流程來驗證電子郵件。
  • 更改用戶的電子郵件而不發送電子郵件鏈接以撤消這些更改。
  • 無需通過 SMS 驗證流程即可使用電話號碼創建新用戶。
  • 無需通過 SMS 驗證流程即可更改用戶的電話號碼。
  • 離線配置處於禁用狀態的用戶,然後控制何時啟用它們。
  • 構建為特定應用程序的用戶管理系統量身定制的自定義用戶控制台。

在你開始之前

要使用 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 個字符之間的字符串,包括 1 到 128 個字符。如果沒有提供,會自動生成一個隨機的uid
email細繩用戶的主要電子郵件。必須是一個有效的E-mail地址。
emailVerified布爾值用戶的主要電子郵件是否經過驗證。如果未提供,則默認為false
phoneNumber細繩用戶的主要電話號碼。必須是符合 E.164 規範的有效電話號碼。
password細繩用戶的原始未散列密碼。長度必須至少為六個字符。
displayName細繩用戶的顯示名稱。
photoURL細繩用戶的照片 URL。
disabled布爾值用戶是否被禁用。殘疾人為truefalse啟用。如果未提供,則默認為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布爾值用戶是否被禁用。殘疾人為truefalse啟用。

當更新成功完成時,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.");

當刪除成功完成時,delete user 方法返回一個空結果。

如果提供的uid與現有用戶不對應,或者由於任何其他原因無法刪除用戶,則 delete user 方法會引發錯誤。有關錯誤代碼的完整列表,包括描述和解決步驟,請參閱管理員身份驗證 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}");
}

delete users 方法返回無法刪除的用戶的失敗列表。有關錯誤代碼的完整列表,包括描述和解決步驟,請參閱管理員身份驗證 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 身份驗證後端為密碼用戶散列的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. 單擊保存