Gestione programmatica degli utenti
Questo documento mostra come utilizzare l'SDK Identity Platform Admin per gestire gli utenti in modo programmatico. Admin SDK ti consente di eseguire un'ampia gamma di attività amministrative comuni, come la creazione, la ricerca e la modifica degli utenti.
Prima di iniziare
Come acquisire un utente
Ottenere un utente in base all'ID
Il modo principale per identificare un utente è tramite il suo uid
:
Node.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); });
Java
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))
Go
// 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}");
Attirare l'utente via email
Puoi anche chiedere a un utente di utilizzare il suo indirizzo email:
Node.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); });
Java
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))
Go
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}");
Tieni presente che puoi cercare solo utilizzando gli indirizzi email principali, non quelli specifici del provider. Ad esempio, se un account Facebook con l'indirizzo email facebookUser@example.com
è collegato a un utente esistente con l'indirizzo email user@example.com
, la chiamata all'indirizzo getUserByEmail("facebookUser@example.com")
non restituirà risultati. La chiamata a getUserByEmail("user@example.com")
restituirà
l'utente previsto.
L'indirizzo email principale dipende dalle impostazioni di collegamento dell'account:
- Collega account che utilizzano lo stesso indirizzo email: l'indirizzo email principale è il primo indirizzo utilizzato per accedere, a meno che non venga aggiornato manualmente.
- Crea più account per ogni provider di identità: l'indirizzo email principale viene impostato solo quando viene creato un utente con password, a meno che non venga aggiornato manualmente.
Ottenere un utente tramite il numero di telefono
Se un utente ha un numero di telefono, puoi cercarlo utilizzandolo:
Node.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); });
Java
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))
Go
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}");
Recuperare collettivamente i dati utente
Puoi anche recuperare un elenco di utenti in base agli identificatori da te forniti. Puoi identificare gli utenti tramite l'uid, l'indirizzo email o il numero di telefono. È possibile fornire un massimo di 100 identificatori in una singola chiamata. Gli identificatori possono contenere una combinazione di tipi:
Node.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); });
Java
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)
Go
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}"); }
Questo metodo restituisce un elenco delle stesse dimensioni dell'elenco di input, in cui ogni voce contiene il valore UserRecord
corrispondente o un errore e indica il motivo per cui non è stato possibile cercare l'identificatore.
Utenti della scheda
Il codice seguente mostra come elencare tutti gli utenti:
Node.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();
Java
// 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)
Go
// 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}"); }
Gli utenti vengono restituiti in batch, ordinati in base al uid
. Ogni gruppo di risultati contiene un elenco di utenti e un token della pagina successiva utilizzato per recuperare il batch successivo.
Una volta che tutti gli utenti sono stati elencati, non viene restituito alcun pageToken
.
Il campo maxResult
consente di specificare la dimensione massima del batch. Il valore predefinito e massimo è 1000.
Elenco degli hash delle password utente
Poiché gli hash delle password sono sensibili, l'SDK Admin non li restituisce
a meno che l'utente non disponga dell'autorizzazione
firebaseauth.configs.getHashConfig
. Questa autorizzazione non è concessa da alcun ruolo predefinito. Per concedere l'autorizzazione:
Crea un ruolo personalizzato che conceda l'autorizzazione
firebaseauth.configs.getHashConfig
.Concedi il ruolo personalizzato all'account utente o di servizio.
Le chiamate successive a listUsers()
da parte degli utenti con questo ruolo personalizzato
includeranno i campi passwordHash
e passwordSalt
.
Creazione di un utente
La creazione di nuovi utenti evita in modo programmatico alcune restrizioni applicate agli utenti finali. Non sei soggetto a limitazioni o limitazione di frequenza e puoi bypassare il normale processo di verifica per email e numeri di telefono.
Per creare un nuovo utente:
Node.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); });
Java
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))
Go
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}");
Puoi impostare qualsiasi proprietà tra quelle di seguito su un nuovo utente. Tutte le proprietà sono facoltative.
Proprietà | Tipo | Descrizione |
---|---|---|
uid |
string |
Il uid da assegnare all'utente appena creato. Deve essere una stringa compresa tra 1 e 128 caratteri inclusi. Se non viene specificato, verrà generato automaticamente un
uid casuale.
|
email |
string | L'indirizzo email principale dell'utente. L'indirizzo email deve essere valido. |
emailVerified |
boolean |
Se l'indirizzo email principale dell'utente è stato verificato o meno. Se non viene specificato, il valore predefinito è false .
|
phoneNumber |
string | Il numero di telefono principale dell'utente. Deve essere un numero di telefono valido conforme alla specifica E.164. |
password |
string | La password dell'utente non elaborata e non sottoposta ad hashing. Deve avere una lunghezza di almeno sei caratteri. |
displayName |
string | Il nome visualizzato dell'utente. |
photoURL |
string | L'URL della foto dell'utente. |
disabled |
boolean |
Indica se l'utente è disattivato o meno. true per disabilitato;
false per abilitato. Se non viene specificato, il valore predefinito è false .
|
Aggiornamento di un utente
Node.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); });
Java
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))
Go
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}");
Puoi aggiornare qualsiasi proprietà utente riportata di seguito. Tutte le proprietà sono facoltative. Se una proprietà non è specificata, il suo valore rimarrà invariato.
Proprietà | Tipo | Descrizione |
---|---|---|
email |
string | Il nuovo indirizzo email principale dell'utente. L'indirizzo email deve essere valido. |
emailVerified |
boolean |
Se l'indirizzo email principale dell'utente è stato verificato o meno. Se non viene specificato, il valore predefinito è false .
|
phoneNumber |
string |
Il nuovo numero di telefono principale dell'utente. Deve essere un numero di telefono valido conforme alla specifica E.164. Imposta su null per cancellare il numero di telefono
esistente dell'utente.
|
password |
string | La nuova password non elaborata e non sottoposta ad hashing dell'utente. Deve avere una lunghezza di almeno sei caratteri. |
displayName |
stringa | null |
Il nuovo nome visualizzato dell'utente. Imposta su null per cancellare il nome visualizzato esistente dell'utente.
|
photoURL |
stringa | null |
L'URL della nuova foto dell'utente. Impostalo su null per cancellare
l'URL della foto esistente dell'utente. Se non è null , deve essere un URL valido.
|
disabled |
boolean |
Indica se l'utente è disattivato o meno. true per disabilitato;
false per abilitato.
|
Eliminare un utente
Puoi eliminare un utente con il suo uid
:
Node.js
getAuth() .deleteUser(uid) .then(() => { console.log('Successfully deleted user'); }) .catch((error) => { console.log('Error deleting user:', error); });
Java
FirebaseAuth.getInstance().deleteUser(uid); System.out.println("Successfully deleted user.");
Python
auth.delete_user(uid) print('Successfully deleted user')
Go
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.");
Elimina più utenti
Puoi anche eliminare più utenti contemporaneamente:
Node.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); });
Java
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))
Go
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}"); }
Il metodo Elimina utenti restituisce un elenco di errori per gli utenti che non è stato possibile eliminare.
Passaggi successivi
- Eseguire la migrazione degli utenti da un'app esistente a Identity Platform
- Gestisci i provider SAML e OIDC in modo programmatico.