Crea un utente
Per creare un nuovo utente, hai a disposizione le seguenti opzioni:
Dalla tua app: crea un nuovo utente nel tuo progetto Firebase chiamando il metodo
CreateUserWithEmailAndPasswordo accedendo per la prima volta con un provider di identità federata, ad esempio Accedi con Google o Accesso con Facebook.Nella console Firebase: crea un nuovo utente autenticato con password nella scheda Sicurezza > Autenticazione > Utenti.
Recuperare l'utente che ha eseguito l'accesso
Il modo consigliato per ottenere l'utente corrente è impostare un listener sull'oggetto Auth:
Firebase.Auth.FirebaseAuth auth; Firebase.Auth.FirebaseUser user; // Handle initialization of the necessary firebase modules: void InitializeFirebase() { Debug.Log("Setting up Firebase Auth"); auth = Firebase.Auth.FirebaseAuth.DefaultInstance; auth.StateChanged += AuthStateChanged; AuthStateChanged(this, null); } // Track state changes of the auth object. void AuthStateChanged(object sender, System.EventArgs eventArgs) { if (auth.CurrentUser != user) { bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null; if (!signedIn && user != null) { Debug.Log("Signed out " + user.UserId); } user = auth.CurrentUser; if (signedIn) { Debug.Log("Signed in " + user.UserId); } } } // Handle removing subscription and reference to the Auth instance. // Automatically called by a Monobehaviour after Destroy is called on it. void OnDestroy() { auth.StateChanged -= AuthStateChanged; auth = null; }
Utilizzando un listener, ti assicuri che l'oggetto Auth non si trovi in uno stato intermedio, ad esempio di inizializzazione, quando recuperi l'utente corrente.
Puoi anche ottenere l'utente che ha eseguito l'accesso chiamando CurrentUser. Se un utente non ha eseguito l'accesso, CurrentUser restituirà un valore nullo. Se un utente ha eseguito la disconnessione,
il valore di IsValid() dell'utente restituirà false.
Persistere le credenziali di un utente
Le credenziali dell'utente vengono archiviate nel keystore locale dopo che l'utente ha eseguito l'accesso. La cache locale delle credenziali utente può essere eliminata disconnettendo l'utente. Il keystore è specifico della piattaforma:
- Piattaforme Apple: Keychain Services.
- Android: Android Keystore.
- Windows: API Credential Management.
- OS X: Servizi portachiavi.
- Linux: libsecret, che l'utente deve aver installato.
Ottenere il profilo di un utente
Per ottenere le informazioni del profilo di un utente, utilizza i metodi di accesso di un'istanza di
Firebase.Auth.FirebaseUser. Ad esempio:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; if (user != null) { string name = user.DisplayName; string email = user.Email; System.Uri photo_url = user.PhotoUrl; // The user's Id, unique to the Firebase project. // Do NOT use this value to authenticate with your backend server, if you // have one; use User.TokenAsync() instead. string uid = user.UserId; }
Ottenere le informazioni del profilo specifiche del fornitore di un utente
Per ottenere le informazioni del profilo recuperate dai provider di accesso collegati a un utente, utilizza il metodo ProviderData. Ad esempio:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; if (user != null) { foreach (var profile in user.ProviderData) { // Id of the provider (ex: google.com) string providerId = profile.ProviderId; // UID specific to the provider string uid = profile.UserId; // Name, email address, and profile photo Url string name = profile.DisplayName; string email = profile.Email; System.Uri photoUrl = profile.PhotoUrl; } }
Aggiornare il profilo di un utente
Puoi aggiornare le informazioni di base del profilo di un utente, ovvero il nome visualizzato
e l'URL della foto del profilo, con il metodo UpdateUserProfile. Ad esempio:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; if (user != null) { Firebase.Auth.UserProfile profile = new Firebase.Auth.UserProfile { DisplayName = "Jane Q. User", PhotoUrl = new System.Uri("https://example.com/jane-q-user/profile.jpg"), }; user.UpdateUserProfileAsync(profile).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("UpdateUserProfileAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("UpdateUserProfileAsync encountered an error: " + task.Exception); return; } Debug.Log("User profile updated successfully."); }); }
Impostare l'indirizzo email di un utente
Puoi impostare l'indirizzo email di un utente con il metodo UpdateEmail. Ad esempio:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; if (user != null) { user.UpdateEmailAsync("user@example.com").ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("UpdateEmailAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("UpdateEmailAsync encountered an error: " + task.Exception); return; } Debug.Log("User email updated successfully."); }); }
Inviare un'email di verifica a un utente
Puoi inviare un'email di verifica dell'indirizzo a un utente con il
metodo SendEmailVerification. Ad esempio:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; if (user != null) { user.SendEmailVerificationAsync().ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("SendEmailVerificationAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("SendEmailVerificationAsync encountered an error: " + task.Exception); return; } Debug.Log("Email sent successfully."); }); }
Puoi personalizzare il modello di email utilizzato nella scheda Sicurezza > Autenticazione > Modelli della console Firebase. Consulta Modelli email nel Centro assistenza Firebase.
Impostare la password di un utente
Puoi impostare la password di un utente con il metodo UpdatePassword. Ad esempio:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; string newPassword = "SOME-SECURE-PASSWORD"; if (user != null) { user.UpdatePasswordAsync(newPassword).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("UpdatePasswordAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("UpdatePasswordAsync encountered an error: " + task.Exception); return; } Debug.Log("Password updated successfully."); }); }
Inviare un'email di reimpostazione password
Puoi inviare un'email di reimpostazione della password a un utente con il metodo SendPasswordResetEmail. Ad esempio:
string emailAddress = "user@example.com"; if (user != null) { auth.SendPasswordResetEmailAsync(emailAddress).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("SendPasswordResetEmailAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("SendPasswordResetEmailAsync encountered an error: " + task.Exception); return; } Debug.Log("Password reset email sent successfully."); }); }
Puoi personalizzare il modello di email utilizzato nella scheda Sicurezza > Autenticazione > Modelli della console Firebase. Consulta Modelli email nel Centro assistenza Firebase.
Puoi anche inviare email di reimpostazione della password dalla console Firebase.
Eliminare un utente
Puoi eliminare un account utente con il metodo Delete. Ad esempio:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; if (user != null) { user.DeleteAsync().ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("DeleteAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("DeleteAsync encountered an error: " + task.Exception); return; } Debug.Log("User deleted successfully."); }); }
Puoi anche eliminare gli utenti nella console Firebase nella scheda Sicurezza > Autenticazione > Utenti.
Eseguire nuovamente l'autenticazione di un utente
Alcune azioni sensibili alla sicurezza, come l'eliminazione di un account, l'impostazione di un indirizzo email principale e la modifica di una password, richiedono che l'utente abbia eseguito l'accesso di recente. Se esegui una di queste azioni e l'utente ha eseguito l'accesso troppo tempo fa, l'azione non va a buon fine.
In questo caso, esegui nuovamente l'autenticazione dell'utente ottenendo nuove credenziali di accesso
e trasmettendole a Reauthenticate. Ad esempio:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; // Get auth credentials from the user for re-authentication. The example below shows // email and password credentials but there are multiple possible providers, // such as GoogleAuthProvider or FacebookAuthProvider. Firebase.Auth.Credential credential = Firebase.Auth.EmailAuthProvider.GetCredential("user@example.com", "password1234"); if (user != null) { user.ReauthenticateAsync(credential).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("ReauthenticateAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("ReauthenticateAsync encountered an error: " + task.Exception); return; } Debug.Log("User reauthenticated successfully."); }); }
Importare gli account utente
Puoi importare gli account utente da un file nel tuo progetto Firebase utilizzando il comando
auth:import dell'interfaccia a riga di comando di Firebase. Ad esempio:
firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14