管理用戶

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

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

在你開始之前

要使用 Firebase Admin SDK 提供的用戶管理 API,您必須擁有服務帳號。按照安裝說明有關如何初始化管理SDK的詳細信息。

檢索用戶數據

識別用戶的主要方式是通過uid ,該用戶的唯一標識符。管理SDK提供了一種方法,它允許通過獲取其用戶的個人資料信息uid

節點.js

admin
  .auth()
  .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}");

此方法返回UserRecord對象對應於所述用戶uid提供給該方法。

如果所提供的uid不屬於現有用戶或用戶不能被獲取任何其他原因,上述方法引發錯誤。有關錯誤代碼,包括說明和解決步驟的完整列表,請參閱管理員驗證API錯誤

在某些情況下,你將擁有一個用戶的電子郵件,而不是他們的uid 。 Firebase Admin SDK 支持通過電子郵件查找用戶信息:

節點.js

admin
  .auth()
  .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 會引發錯誤。有關錯誤代碼,包括說明和解決步驟的完整列表,請參閱Admin認證API錯誤

在其他情況下,你將有一個用戶的電話號碼,而不是他們的uid 。 Firebase Admin SDK 支持使用電話號碼查找用戶信息:

節點.js

admin
  .auth()
  .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 會引發錯誤。有關錯誤代碼,包括說明和解決步驟的完整列表,請參閱Admin認證API錯誤

批量檢索用戶數據

Firebase Admin SDK 還允許根據您提供的標識符檢索用戶列表。您可以通過用戶 ID、電子郵件或電話號碼來識別用戶。一次調用中最多可以提供 100 個標識符。標識符可以包含多種類型:

節點.js

admin
  .auth()
  .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或指示為什麼該標識符不能夠被查找錯誤。有關錯誤代碼,包括說明和解決步驟的完整列表,請參閱Admin認證API錯誤

創建用戶

Admin SDK 提供了一種方法,可讓您創建新的 Firebase 身份驗證用戶。此方法接受一個包含要包含在新創建的用戶帳戶中的配置文件信息的對象:

節點.js

admin
  .auth()
  .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}");

默認情況下,火力地堡認證會產生一個隨機uid為新用戶。如果你不是要指定自己uid為新用戶,可以將其包含傳遞給用戶創造方法的參數:

節點.js

admin
  .auth()
  .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. create user 操作支持的屬性

財產類型描述
uid細繩uid分配給新創建的用戶。必須是長度介於 1 到 128 個字符之間的字符串(含)。如果沒有提供,隨機uid會自動生成。
email細繩用戶的主要電子郵件。必須是一個有效的E-mail地址。
emailVerified布爾值是否驗證用戶的主要電子郵件。如果沒有提供,默認是false
phoneNumber細繩用戶的主要電話號碼。必須是符合 E.164 規範的有效電話號碼。
password細繩用戶的原始、未散列的密碼。長度必須至少為六個字符。
displayName細繩用戶的顯示名稱。
photoURL細繩用戶的照片 URL。
disabled布爾值用戶是否被禁用。 true為殘疾人; false的啟用。如果沒有提供,默認是false

用戶創建方法返回一個UserRecord對象為新創建的用戶。

如果所提供的uid ,電子郵件或電話號碼已被使用的現有用戶或用戶不能因任何其他原因被創建,上述方法因錯誤而失敗。有關錯誤代碼,包括說明和解決步驟的完整列表,請參閱Admin認證API錯誤

更新用戶

Firebase Admin SDK 有助於修改現有用戶的數據。你需要指定一個uid與屬性更新用戶一起:

節點.js

admin
  .auth()
  .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的啟用。

更新用戶方法返回一個更新UserRecord更新成功完成時對象。

如果提供的uid不符合現有的用戶,所提供的電子郵件或電話號碼已被使用的現有用戶,或用戶不能為任何其他原因而更新,上述方法因錯誤而失敗。有關錯誤代碼,包括說明和解決步驟的完整列表,請參閱Admin認證API錯誤

刪除用戶

在火力地堡管理SDK允許通過其刪除現有用戶uid

節點.js

admin
  .auth()
  .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不對應於現有用戶或用戶不能因任何其他原因被刪除,則刪除用戶的方法引發錯誤。有關錯誤代碼,包括說明和解決步驟的完整列表,請參閱Admin認證API錯誤

刪除多個用戶

Firebase Admin SDK 還可以一次刪除多個用戶。但是,請注意,使用類似的方法deleteUsers(uids)刪除一次多用戶將不會觸發onDelete()用於火力地堡雲功能的事件處理程序。這是因為批量刪除不會在每個用戶上觸髮用戶刪除事件。如果您希望為每個已刪除的用戶觸髮用戶刪除事件,請一次刪除一個用戶。

節點.js

admin
  .auth()
  .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 方法返回無法刪除的用戶的失敗列表。有關錯誤代碼,包括說明和解決步驟的完整列表,請參閱Admin認證API錯誤

列出所有用戶

Firebase Admin SDK 允許批量檢索整個用戶列表:

節點.js

const listAllUsers = (nextPageToken) => {
  // List batch of users, 1000 at a time.
  admin
    .auth()
    .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

有關錯誤代碼,包括說明和解決步驟的完整列表,請參閱Admin認證API錯誤

列出用戶的密碼哈希

這個API還返回passwordSaltpasswordHash散列由火力地堡驗證後台密碼的用戶,如果用戶/服務帳戶用於生成令牌有請求OAuth訪問firebaseauth.configs.getHashConfig許可。否則passwordHashpasswordSalt不會設置。

由於密碼哈希值的敏感性質,火力地堡管理SDK服務帳戶不具有firebaseauth.configs.getHashConfig默認權限。您不能直接添加權限到用戶/服務帳戶,但您可以通過這樣做間接地創建自定義的IAM角色

要創建自定義 IAM 角色:

  1. 轉到IAM和管理面板的角色頁面在谷歌雲端控制台。
  2. 從頁面頂部的下拉列表中選擇您的項目。
  3. 點擊創建角色
  4. 點擊添加權限
  5. 搜索firebaseauth.configs.getHashConfig許可並選擇複選框。
  6. 點擊添加
  7. 單擊創建完成創建新角色。

將創建的自定義角色添加到 IAM 頁面中的用戶/服務帳戶:

  1. IAM和管理面板,選擇IAM
  2. 從成員列表中選擇服務或用戶帳戶進行編輯。
  3. 點擊添加另一個角色
  4. 搜索之前創建的新自定義角色。
  5. 點擊保存