使用 Unity 使用基於密碼的帳戶透過 Firebase 進行身份驗證

您可以使用 Firebase 驗證讓您的使用者使用其電子郵件地址和密碼透過 Firebase 進行身份驗證,並管理您套用的基於密碼的帳戶。

在你開始之前

在使用Firebase 驗證之前,您需要:

  • 註冊您的 Unity 專案並將其配置為使用 Firebase。

    • 如果您的 Unity 專案已使用 Firebase,則它已針對 Firebase 進行註冊和設定。

    • 如果您沒有 Unity 項目,可以下載範例應用程式

  • Firebase Unity SDK (具體來說, FirebaseAuth.unitypackage )加入您的 Unity 專案。

請注意,將 Firebase 新增至 Unity 專案涉及Firebase 控制台和開啟的 Unity 專案中的任務(例如,從控制台下載 Firebase 設定文件,然後將它們移至 Unity 專案中)。

存取Firebase.Auth.FirebaseAuth

FirebaseAuth類別是所有 API 呼叫的網關。它可以透過FirebaseAuth.DefaultInstance存取。
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;

建立基於密碼的帳戶

若要建立具有密碼的新使用者帳戶,請在應用程式的登入代碼中完成以下步驟:

  1. 當新使用者使用應用程式的註冊表單進行註冊時,請完成應用程式要求的所有新帳戶驗證步驟,例如驗證新帳戶的密碼是否正確輸入並滿足您的複雜性要求。
  2. 透過將新使用者的電子郵件地址和密碼傳遞給FirebaseAuth.CreateUserWithEmailAndPassword來建立新帳戶:
    auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task => {
      if (task.IsCanceled) {
        Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled.");
        return;
      }
      if (task.IsFaulted) {
        Debug.LogError("CreateUserWithEmailAndPasswordAsync encountered an error: " + task.Exception);
        return;
      }
    
      // Firebase user has been created.
      Firebase.Auth.AuthResult result = task.Result;
      Debug.LogFormat("Firebase user created successfully: {0} ({1})",
          result.User.DisplayName, result.User.UserId);
    });
    

使用電子郵件地址和密碼登入用戶

使用密碼登入使用者的步驟與建立新帳戶的步驟類似。在應用程式的登入功能中,執行以下操作:

  1. 當使用者登入您的應用程式時,將使用者的電子郵件地址和密碼傳遞給FirebaseAuth.SignInWithEmailAndPassword
    auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task => {
      if (task.IsCanceled) {
        Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");
        return;
      }
      if (task.IsFaulted) {
        Debug.LogError("SignInWithEmailAndPasswordAsync encountered an error: " + task.Exception);
        return;
      }
    
      Firebase.Auth.AuthResult result = task.Result;
      Debug.LogFormat("User signed in successfully: {0} ({1})",
          result.User.DisplayName, result.User.UserId);
    });
    
  2. 您也可以像其他工作流程一樣建立憑證並登入:
    Firebase.Auth.Credential credential =
        Firebase.Auth.EmailAuthProvider.GetCredential(email, password);
    auth.SignInAndRetrieveDataWithCredentialAsync(credential).ContinueWith(task => {
      if (task.IsCanceled) {
        Debug.LogError("SignInAndRetrieveDataWithCredentialAsync was canceled.");
        return;
      }
      if (task.IsFaulted) {
        Debug.LogError("SignInAndRetrieveDataWithCredentialAsync encountered an error: " + task.Exception);
        return;
      }
    
      Firebase.Auth.AuthResult result = task.Result;
      Debug.LogFormat("User signed in successfully: {0} ({1})",
          result.User.DisplayName, result.User.UserId);
    });
    

建議:啟用電子郵件枚舉保護

如果電子郵件地址在必須註冊時未註冊(例如,使用電子郵件地址和密碼登入時)或在必須未使用時已註冊(例如,更改使用者的電子郵件地址時)。雖然這有助於向用戶建議具體補救措施,但惡意行為者也可能濫用它來發現用戶註冊的電子郵件地址。

為了降低此風險,我們建議您使用 Google Cloud gcloud工具為您的專案啟用電子郵件枚舉保護。請注意,啟用此功能會變更 Firebase 驗證的錯誤報告行為:確保您的應用程式不依賴更具體的錯誤。

下一步

使用者首次登入後,系統會建立新的使用者帳戶,並將其連結到使用者登入時所使用的憑證(即使用者名稱和密碼、電話號碼或驗證提供者資訊)。此新帳戶將作為 Firebase 專案的一部分存儲,並且可用於識別專案中每個應用程式中的用戶,無論用戶如何登入。

  • 在您的應用程式中,您可以從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;
    }
    
  • 在 Firebase 即時資料庫和雲端儲存安全性規則中,您可以從auth變數取得登入使用者的唯一使用者 ID,並使用它來控制使用者可以存取哪些資料。

您可以透過將身分驗證提供者憑證連結到現有使用者帳戶,允許使用者使用多個驗證提供者登入您的應用程式。

若要登出用戶,請呼叫SignOut()

auth.SignOut();