在 Unity 中使用電話號碼向 Firebase 驗證

您可以傳送簡訊到使用者的手機,透過 Firebase Authentication 讓使用者登入。使用者使用簡訊中的一次性驗證碼登入。

本文說明如何使用 Firebase SDK 導入電話號碼登入流程。

事前準備

  1. 您必須先將 Firebase Unity SDK (具體來說是 FirebaseAuth.unitypackage) 新增至 Unity 專案,才能使用 Firebase Authentication。

    如需這些初始設定步驟的詳細操作說明,請參閱「將 Firebase 新增至 Unity 專案」。

  2. 如果尚未將應用程式連結至 Firebase 專案,請前往 Firebase 控制台進行連結。
  3. 瞭解電話號碼登入功能的平台需求條件:
    • 電話號碼登入功能僅適用於行動平台。
    • 在 iOS 上,電話號碼登入程序需要實體裝置,無法在模擬器上運作。

安全疑慮

雖然僅使用電話號碼進行驗證很方便,但由於電話號碼的擁有權可以在使用者之間轉移,因此安全性不如其他可用方法。此外,在有多個使用者設定檔的裝置上,任何可接收簡訊的使用者,都能使用裝置的電話號碼登入帳戶。

如果應用程式支援以電話號碼登入,請同時提供更安全的登入方式,並告知使用者以電話號碼登入的安全風險。

為 Firebase 專案啟用電話號碼登入功能

如要讓使用者透過簡訊登入,您必須先為 Firebase 專案啟用電話號碼登入方式:

  1. 在 Firebase 控制台中,依序前往「Security」(安全性) > 「Authentication」(驗證)。
  2. 在「登入方式」分頁中,啟用「電話」登入供應商。
  3. 設定政策,允許或禁止傳送簡訊至特定區域。設定簡訊區域政策,有助於防範應用程式遭到簡訊濫用。如果是新專案,預設政策不允許任何區域。
    1. 在 Firebase 控制台中,依序前往「Security」(安全性) >「Authentication」(驗證) >「Settings」(設定) 分頁標籤。
    2. 在「簡訊區域政策」部分,設定簡訊區域政策。

開始接收 APNs 通知 (僅限 iOS)

如要在 iOS 上使用電話號碼驗證功能,應用程式必須能接收 Firebase 的 APN 通知。當使用者首次在裝置上使用電話號碼登入時,Firebase Authentication 會向裝置傳送靜音推播通知,驗證電話號碼登入要求是否來自您的應用程式。(因此,電話號碼登入功能無法在模擬器上使用)。

如要啟用 APNs 通知,以便與 Firebase Authentication 搭配使用,請按照下列步驟操作:

  1. 在 Xcode 中,為專案啟用推播通知。
  2. 將 APNs 憑證上傳至 Firebase。如果尚未取得 APNs 憑證,請務必前往 Apple Developer Member Center 建立。

    1. 在 Firebase 控制台中,依序前往「 Settings」(設定) >「General」(一般)。接著,按一下 「雲端通訊」分頁標籤。
    2. 按一下「上傳憑證」,上傳開發憑證和/或正式版憑證。至少擇一提供。
    3. 針對每個憑證,選取 .p12 檔案,並提供密碼 (如有)。確認這項憑證的軟體包 ID 與應用程式的軟體包 ID 相符,然後按一下「Save」(儲存)。

將驗證碼傳送至使用者的手機

如要啟動電話號碼登入程序,請向使用者顯示介面,提示他們提供電話號碼,然後呼叫 PhoneAuthProvider.VerifyPhoneNumber,要求 Firebase 透過簡訊將驗證碼傳送至使用者的手機:

  1. 取得使用者的電話號碼。

    法律要求不盡相同,但為確保使用者瞭解相關規定,最佳做法是告知他們,如果使用電話登入,可能會收到驗證簡訊,且須支付標準費率。

  2. 呼叫 PhoneAuthProvider.VerifyPhoneNumber,並傳遞包含使用者電話號碼的 PhoneAuthOptions。
    PhoneAuthProvider provider = PhoneAuthProvider.GetInstance(firebaseAuth);
    provider.VerifyPhoneNumber(
      new Firebase.Auth.PhoneAuthOptions {
        PhoneNumber = phoneNumber,
        TimeoutInMilliseconds = phoneAuthTimeoutMs,
        ForceResendingToken = null
      },
      verificationCompleted: (credential) =&gt {
        // Auto-sms-retrieval or instant validation has succeeded (Android only).
        // There is no need to input the verification code.
        // `credential` can be used instead of calling GetCredential().
      },
      verificationFailed: (error) =&gt {
        // The verification code was not sent.
        // `error` contains a human readable explanation of the problem.
      },
      codeSent: (id, token) =&gt {
        // Verification code was successfully sent via SMS.
        // `id` contains the verification id that will need to passed in with
        // the code from the user when calling GetCredential().
        // `token` can be used if the user requests the code be sent again, to
        // tie the two requests together.
      },
      codeAutoRetrievalTimeout: (id) =&gt {
        // Called when the auto-sms-retrieval has timed out, based on the given
        // timeout parameter.
        // `id` contains the verification id of the request that timed out.
      });
    呼叫 PhoneAuthProvider.VerifyPhoneNumber 時,Firebase、
    • (iOS),則會傳送靜音推播通知至應用程式。
    • Firebase 會將含有驗證碼的簡訊傳送至指定電話號碼,並將驗證 ID 傳遞至完成函式。您必須同時提供驗證碼和驗證 ID,才能讓使用者登入。
  3. 請儲存驗證 ID,並在應用程式載入時還原。這樣一來,即使應用程式在使用者完成登入流程前終止 (例如切換至訊息應用程式時),您仍可確保驗證 ID 有效。

    您可以視需要保留驗證 ID。簡單的方法是使用 UnityEngine.PlayerPrefs 儲存驗證 ID。

如果系統呼叫傳入 codeSent 的回呼,您可以在使用者收到簡訊驗證碼時,提示他們輸入驗證碼。

另一方面,如果系統呼叫 verificationCompleted 的回呼,表示自動驗證成功,您現在可以按照下方說明使用 PhoneAuthCredential。

使用驗證碼登入使用者

使用者向應用程式提供簡訊中的驗證碼後,請根據驗證碼和驗證 ID 建立 PhoneAuthCredential 物件,並將該物件傳遞至 FirebaseAuth.SignInAndRetrieveDataWithCredentialAsync,讓使用者登入。

  1. 向使用者索取驗證碼。
  2. 使用驗證碼和驗證 ID 建立 Credential 物件。
    PhoneAuthCredential credential =
        phoneAuthProvider.GetCredential(verificationId, verificationCode);
        
  3. 使用 PhoneAuthCredential 物件登入使用者:
    auth.SignInAndRetrieveDataWithCredentialAsync(credential).ContinueWith(task =&gt {
      if (task.IsFaulted) {
        Debug.LogError("SignInAndRetrieveDataWithCredentialAsync encountered an error: " +
                       task.Exception);
        return;
      }
    
      FirebaseUser newUser = task.Result.User;
      Debug.Log("User signed in successfully");
      // This should display the phone number.
      Debug.Log("Phone number: " + newUser.PhoneNumber);
      // The phone number providerID is 'phone'.
      Debug.Log("Phone provider ID: " + newUser.ProviderId);
    });

後續步驟

使用者首次登入後,系統會建立新的使用者帳戶,並連結至使用者登入時使用的憑證,也就是使用者名稱和密碼、電話號碼或驗證提供者資訊。這個新帳戶會儲存為 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 Realtime Database 和 Cloud Storage安全性規則中,您可以從 auth 變數取得已登入使用者的專屬使用者 ID,並用來控管使用者可存取的資料。

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

如要登出使用者,請呼叫 SignOut():

auth.SignOut();