Google is committed to advancing racial equity for Black communities. See how.
This page was translated by the Cloud Translation API.
Switch to English

管理用戶

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

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

在你開始之前

要使用Firebase Admin SDK提供的用戶管理API,您必須擁有一個服務帳戶。請遵循安裝說明 ,以獲取有關如何初始化Admin SDK的更多信息。

檢索用戶數據

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

Node.js

 admin.auth().getUser(uid)
  .then(function(userRecord) {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully fetched user data:', userRecord.toJSON());
  })
  .catch(function(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());
 

蟒蛇

 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錯誤

在某些情況下,您將收到用戶的電子郵件,而不是其uid 。 Firebase Admin SDK支持通過電子郵件查找用戶信息:

Node.js

 admin.auth().getUserByEmail(email)
  .then(function(userRecord) {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully fetched user data:', userRecord.toJSON());
  })
  .catch(function(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());
 

蟒蛇

 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 Authentication API Errors

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

Node.js

 admin.auth().getUserByPhoneNumber(phoneNumber)
  .then(function(userRecord) {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully fetched user data:', userRecord.toJSON());
  })
  .catch(function(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());
 

蟒蛇

 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 Authentication API Errors

批量檢索用戶數據

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

Node.js

 admin.auth().getUsers([
    { uid: 'uid1' },
    { email: 'user2@example.com' },
    { phoneNumber: '+15555550003' },
    { providerId: 'google.com', providerUid: 'google_uid4' },
  ])
  .then(function(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(function(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);
}
 

蟒蛇

 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 Authentication API Errors

創建一個用戶

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

Node.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(function(userRecord) {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully created new user:', userRecord.uid);
  })
  .catch(function(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());
 

蟒蛇

 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 ,則可以包含傳遞給用戶創建方法的it參數:

Node.js

 admin.auth().createUser({
  uid: 'some-uid',
  email: 'user@example.com',
  phoneNumber: '+11234567890'
})
  .then(function(userRecord) {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully created new user:', userRecord.uid);
  })
  .catch(function(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());
 

蟒蛇

 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
email 用戶的主要電子郵件。必須是一個有效的E-mail地址。
emailVerified 布爾值用戶的主要電子郵件是否已驗證。如果未提供,則默認值為false
phoneNumber 用戶的主要電話號碼。必須是符合E.164規範的有效電話號碼。
password 用戶的原始密碼。必須至少包含六個字符。
displayName 用戶的顯示名稱。
photoURL 用戶的照片網址。
disabled 布爾值用戶是否被禁用。 true為殘疾人;如果啟用則為false 。如果未提供,則默認值為false

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

如果提供的uid ,電子郵件或電話號碼已被現有用戶使用,或者由於任何其他原因而無法創建該用戶,則上述方法將失敗並顯示錯誤。有關錯誤代碼的完整列表,包括描述和解決步驟,請參閱Admin Authentication API Errors

更新用戶

Firebase Admin SDK有助於修改現有用戶的數據。您需要指定一個uid以及要為該用戶更新的屬性:

Node.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(function(userRecord) {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully updated user', userRecord.toJSON());
  })
  .catch(function(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());
 

蟒蛇

 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 Authentication API Errors

刪除用戶

Firebase Admin SDK允許通過其uid刪除現有用戶:

Node.js

 admin.auth().deleteUser(uid)
  .then(function() {
    console.log('Successfully deleted user');
  })
  .catch(function(error) {
    console.log('Error deleting user:', error);
  });
 

爪哇

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

蟒蛇

 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與現有用戶不對應,或者由於任何其他原因無法刪除該用戶,則delete user方法將引發錯誤。有關錯誤代碼的完整列表,包括描述和解決步驟,請參閱Admin Authentication API Errors

刪除多個用戶

Firebase Admin SDK還可以一次刪除多個用戶:

Node.js

 admin.auth().deleteUsers([uid1, uid2, uid3])
  .then(function(deleteUsersResult) {
    console.log('Successfully deleted ' + deleteUsersResult.successCount + ' users');
    console.log('Failed to delete ' +  deleteUsersResult.failureCount + ' users');
    deleteUsersResult.errors.forEach(function(err) {
      console.log(err.error.toJSON());
    });
  })
  .catch(function(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());
}
 

蟒蛇

 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 Authentication API Errors

列出所有用戶

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

Node.js

 function listAllUsers(nextPageToken) {
  // List batch of users, 1000 at a time.
  admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
      listUsersResult.users.forEach(function(userRecord) {
        console.log('user', userRecord.toJSON());
      });
      if (listUsersResult.pageToken) {
        // List next batch of users.
        listAllUsers(listUsersResult.pageToken);
      }
    })
    .catch(function(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());
}
 

蟒蛇

 # 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().GetEnumerator();
while (await responses.MoveNext())
{
    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).GetEnumerator();
while (await enumerator.MoveNext())
{
    ExportedUserRecord user = enumerator.Current;
    Console.WriteLine($"User: {user.Uid}");
}

 

每一批結果包含一個用戶列表和用於列出下一批用戶的下一頁標記。列出所有用戶後,將不返回pageToken

如果未指定maxResults字段,則默認使用每批1000個用戶。這也是一次允許列出的最大用戶數。任何大於最大值的值都將引發參數錯誤。如果未指定pageToken ,則該操作將從開始按uid順序列出用戶。

有關錯誤代碼的完整列表,包括描述和解決步驟,請參閱Admin Authentication API Errors

列出的用戶的密碼哈希

如果用於生成請求OAuth訪問令牌的用戶/服務帳戶具有firebaseauth.configs.getHashConfig權限,則此API還會為密碼用戶返回由Firebase Auth後端哈希處理的passwordSaltpasswordHash 。否則,將不會設置passwordHashpasswordSalt

由於密碼哈希的敏感性,默認情況下,Firebase Admin SDK服務帳戶不具有firebaseauth.configs.getHashConfig權限。您不能直接向用戶/服務帳戶添加權限,但是可以通過創建自定義IAM角色間接添加權限。

要創建自定義IAM角色,請執行以下操作:

  1. 轉到GCP控制台中IAM和管理面板中的“ 角色”頁面。
  2. 從頁面頂部的下拉菜單中選擇您的項目。
  3. 單擊創建角色
  4. 點擊添加權限
  5. 搜索firebaseauth.configs.getHashConfig權限,然後選中該複選框。
  6. 點擊添加
  7. 單擊創建以完成創建新角色。

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

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