在你開始之前
在使用Firebase 驗證之前,您需要:
- 將您的 Unity 專案註冊到 Firebase 專案。
- 將Firebase Unity SDK (具體來說,
FirebaseAuth.unitypackage
)加入您的 Unity 專案。
在將 Firebase 新增至 Unity 專案中尋找這些初始設定步驟的詳細說明。
- 取得項目的伺服器金鑰:
- 前往項目設定中的服務帳戶頁面。
- 點選服務帳戶頁面Firebase Admin SDK部分底部的產生新私鑰。
- 新服務帳戶的公鑰/私鑰對會自動儲存在您的電腦上。將此文件複製到您的身份驗證伺服器。
使用 Firebase 進行身份驗證
FirebaseAuth
類別是所有 API 呼叫的網關。它可以透過FirebaseAuth.DefaultInstance存取。Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
使用身份驗證伺服器中的令牌呼叫Firebase.Auth.FirebaseAuth.SignInWithCustomTokenAsync
。
- 當使用者登入您的應用程式時,將他們的登入憑證(例如使用者名稱和密碼)發送到您的身份驗證伺服器。您的伺服器檢查憑證並傳回自訂令牌(如果它們有效)。
- 從身份驗證伺服器收到自訂令牌後,將其傳遞給
Firebase.Auth.FirebaseAuth.SignInWithCustomTokenAsync
以登入使用者:auth.SignInWithCustomTokenAsync(custom_token).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("SignInWithCustomTokenAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("SignInWithCustomTokenAsync 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); });
下一步
使用者首次登入後,系統會建立新的使用者帳戶,並將其連結到使用者登入時所使用的憑證(即使用者名稱和密碼、電話號碼或驗證提供者資訊)。此新帳戶將作為 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();