在 Firebase 中管理使用者

新增使用者

您可以透過下列方式建立新使用者:

  • 從應用程式:呼叫 CreateUserWithEmailAndPassword 方法,在 Firebase 專案中建立新使用者,或是使用聯合身分識別資訊提供者 (例如 Google 登入Facebook 登入) 首次登入使用者。

  • Firebase 控制台中:在「Security」(安全性) >「Authentication」(驗證) >「Users」(使用者) 分頁中,建立新的密碼驗證使用者

取得目前登入的使用者

建議您在驗證物件上設定事件監聽器,藉此取得目前使用者:

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;
}

使用事件監聽器可確保您取得目前使用者時,驗證物件不會處於中繼狀態 (例如初始化)。

您也可以呼叫 CurrentUser,取得目前登入的使用者。如果使用者未登入,CurrentUser 會傳回空值。如果使用者已登出,系統會傳回 IsValid() 的 false 值。

保存使用者憑證

使用者登入後,系統會將憑證儲存在本機金鑰儲存區。登出使用者即可刪除本機快取的使用者憑證。金鑰儲存區會因平台而異:

取得使用者個人資料

如要取得使用者的個人資料資訊,請使用 Firebase.Auth.FirebaseUser 執行個體的存取子方法。例如:

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;
}

取得使用者的特定供應商個人資料資訊

如要取得從連結至使用者的登入供應商擷取的個人資料,請使用 ProviderData 方法。例如:

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;
  }
}

更新使用者個人資料

您可以使用 UpdateUserProfile 方法,更新使用者的基本個人資料資訊,包括顯示名稱和個人資料相片網址。例如:

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

設定使用者的電子郵件地址

您可以使用 UpdateEmail 方法設定使用者的電子郵件地址。例如:

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

傳送驗證電子郵件給使用者

您可以使用 SendEmailVerification 方法,傳送地址驗證電子郵件給使用者。例如:

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

如要自訂 Firebase 控制台的「安全性」 >「驗證」 >「範本」分頁中使用的電子郵件範本,請參閱 Firebase 說明中心的「電子郵件範本」。

設定使用者密碼

您可以使用 UpdatePassword 方法設定使用者密碼。例如:

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

傳送密碼重設電子郵件

您可以使用 SendPasswordResetEmail 方法傳送密碼重設電子郵件給使用者。例如:

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

如要自訂 Firebase 控制台的「安全性」 >「驗證」 >「範本」分頁中使用的電子郵件範本,請參閱 Firebase 說明中心的「電子郵件範本」。

您也可以從 Firebase 控制台傳送重設密碼電子郵件。

刪除使用者

您可以使用 Delete 方法刪除使用者帳戶。例如:

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

您也可以在 Firebase 控制台中依序點選「Security」(安全性) >「Authentication」(驗證) >「Users」(使用者) 分頁標籤,刪除使用者。

重新驗證使用者

執行部分安全性敏感操作 (例如刪除帳戶設定主要電子郵件地址變更密碼) 時,使用者必須最近登入帳戶。如果您執行上述任一動作,但使用者登入時間已過長,動作就會失敗。

發生這種情況時,請向使用者索取新的登入憑證,並將憑證傳遞至 Reauthenticate,重新驗證使用者。例如:

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

匯入使用者帳戶

您可以使用 Firebase CLI 的 auth:import 指令,將檔案中的使用者帳戶匯入 Firebase 專案。例如:

firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14