Gestione programmatica degli utenti
Questo documento mostra come utilizzare l'SDK Admin di Identity Platform per gestire in modo programmatico. L'SDK Admin ti consente di eseguire una serie di attività amministrative comuni, come la creazione, la ricerca la modifica degli utenti.
Prima di iniziare
Acquisizione di un utente
Acquisire un utente per ID
Il modo principale per identificare un utente è tramite 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))
Vai
// 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}");
Ricevere un 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))
Vai
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 eseguire ricerche solo utilizzando indirizzi email principali, non quelli specifici del fornitore
email. Ad esempio, se un account Facebook con l'indirizzo
facebookUser@example.com
è collegato a un utente esistente con
invia l'email user@example.com
, chiama il numero getUserByEmail("facebookUser@example.com")
non produrrà risultati. La chiamata al numero getUserByEmail("user@example.com")
verrà ripristinata
l'utente previsto.
L'indirizzo email principale dipende dalle impostazioni di collegamento dell'account:
- Collega gli account che utilizzano lo stesso indirizzo email: l'indirizzo email principale è il primo. utilizzato per effettuare l'accesso, a meno che non vengano aggiornati 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.
Raggiungere un utente tramite il numero di telefono
Se un utente dispone di 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))
Vai
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 i dati utente in blocco
Puoi anche recuperare un elenco di utenti in base agli identificatori che fornisci. Puoi identificare gli utenti in base all'uid, all'indirizzo email o al numero di telefono. Un massimo di 100 gli identificatori possono essere forniti in una singola chiamata. Gli identificatori possono contenere una combinazione 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)
Vai
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, con ogni voce
contenente il valore UserRecord
corrispondente o un errore, che indica il motivo
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)
Vai
// 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 relativo uid
. Ogni gruppo di risultati
contiene un elenco di utenti e un token per la pagina successiva utilizzato per recuperare il batch successivo.
Quando tutti gli utenti sono stati elencati, non viene restituito alcun pageToken
.
Il campo maxResult
specifica la dimensione massima del batch. I valori predefiniti e
il valore 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 abbia firebaseauth.configs.getHashConfig
autorizzazione. Questa autorizzazione non viene concessa da nessun ruolo predefinito. Per concederla:
Creare un ruolo personalizzato che concede 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
includi i campi passwordHash
e passwordSalt
.
Creazione di un utente
La creazione di nuovi utenti in modo programmatico evita alcune limitazioni imposte alla fine utenti. Non sei soggetto a limitazione o limitazione di frequenza e puoi bypassare il normale procedura di verifica di 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))
Vai
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 una qualsiasi delle seguenti proprietà su un nuovo utente. Tutte le proprietà sono facoltativo.
Proprietà | Tipo | Descrizione |
---|---|---|
uid |
string |
Il uid da assegnare all'utente appena creato. Deve essere un
stringa di lunghezza compresa tra 1 e 128 caratteri (inclusi). Se non viene specificato,
verrà generato automaticamente 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
Il valore predefinito è false .
|
phoneNumber |
string | Il numero di telefono principale dell'utente. Deve essere conforme a una specifica E.164 valida numero di telefono. |
password |
string | La password non elaborata e non sottoposta ad hashing dell'utente. Deve avere una lunghezza di almeno 6 caratteri. |
displayName |
string | L'account utente il nome visualizzato. |
photoURL |
string | L'URL della foto dell'utente. |
disabled |
boolean |
Indica se l'utente è disattivato o meno. true per disabilitato;
false per attivato. 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))
Vai
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 di seguito. Tutte le proprietà sono facoltative. Se una proprietà non viene 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
Il valore predefinito è false .
|
phoneNumber |
string |
Il nuovo numero di telefono principale dell'utente. Deve essere conforme a una specifica E.164 valida
numero di telefono. Imposta su null per cancellare i dati esistenti dell'utente
numero di telefono.
|
password |
string | La nuova password non elaborata e non sottoposta ad hashing dell'utente. Deve avere una lunghezza di almeno 6 caratteri. |
displayName |
stringa | null |
L'account utente nuovo nome visualizzato. Imposta su null per cancellare
il nome visualizzato esistente.
|
photoURL |
stringa | null |
L'account utente il nuovo URL della foto. Imposta su null per cancellare
URL della foto esistente. Se non null , deve essere un URL valido.
|
disabled |
boolean |
Indica se l'utente è disattivato o meno. true per disabilitato;
false per attivato.
|
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')
Vai
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))
Vai
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 sono non possono essere eliminati.
Passaggi successivi
- Eseguire la migrazione degli utenti da un'app esistente a Identity Platform
- Gestisci i provider SAML e OIDC in modo programmatico.