使用電話號碼在 Android 上透過 Firebase 進行身份驗證

您可以使用 Firebase 身份驗證,透過向使用者的手機發送簡訊來登入使用者。使用者使用 SMS 訊息中包含的一次性代碼登入。

將電話號碼登入新增至應用程式最簡單的方法是使用FirebaseUI ,其中包括一個下拉登入小部件,該小部件可實現電話號碼登入的登入流程以及基於密碼的聯合登入。本文檔說明如何使用 Firebase SDK 實作電話號碼登入流程。

在你開始之前

  1. 如果您尚未將 Firebase 新增至您的 Android 專案中,請將其新增至您的 Android 專案中。
  2. 模組(應用程式層級)Gradle 檔案(通常<project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle )中,新增Firebase 驗證的依賴項Android 的庫。我們建議使用Firebase Android BoM來控制函式庫版本控制。
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.7.4"))
    
        // Add the dependency for the Firebase Authentication library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-auth")
    }
    

    透過使用Firebase Android BoM ,您的應用程式將始終使用 Firebase Android 程式庫的相容版本。

    (替代方法)在不使用 BoM 的情況下新增 Firebase 庫依賴項

    如果您選擇不使用 Firebase BoM,則必須在其依賴項行中指定每個 Firebase 庫版本。

    請注意,如果您在應用程式中使用多個Firebase 程式庫,我們強烈建議使用 BoM 來管理程式庫版本,這可確保所有版本相容。

    dependencies {
        // Add the dependency for the Firebase Authentication library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-auth:22.3.1")
    }
    
    正在尋找 Kotlin 特定的庫模組?2023 年 10 月(Firebase BoM 32.5.0)開始,Kotlin 和 Java 開發人員都可以依賴主庫模組(有關詳細信息,請參閱有關此計劃的常見問題解答)。
  3. 如果您尚未將應用程式連線至 Firebase 項目,請從Firebase 控制台執行此操作。
  4. 如果您尚未在Firebase 控制台中設定已套用的 SHA-1 哈希,請執行此操作。有關查找應用程式的 SHA-1 雜湊值的信息,請參閱驗證您的用戶端

安全問題

僅使用電話號碼進行身份驗證雖然方便,但安全性低於其他可用方法,因為電話號碼的所有權可以在用戶之間輕鬆轉移。此外,在具有多個使用者設定檔的裝置上,任何可以接收 SMS 訊息的使用者都可以使用裝置的電話號碼登入帳戶。

如果您在應用程式中使用基於電話號碼的登入方式,則應與更安全的登入方法一起提供,並告知使用者使用電話號碼登入的安全性權衡。

為您的 Firebase 專案啟用電話號碼登錄

若要透過簡訊登入用戶,您必須先為您的 Firebase 專案啟用電話號碼登入方法:

  1. Firebase 控制台中,開啟「驗證」部分。
  2. 登入方法頁面上,啟用電話號碼登入方法。

Firebase 的電話號碼登入請求配額足夠高,大多數應用程式不會受到影響。但是,如果您需要透過電話驗證登入大量用戶,則可能需要升級定價方案。請參閱定價頁面。

啟用應用程式驗證

若要使用電話號碼驗證,Firebase 必須能夠驗證電話號碼登入要求是否來自您的應用程式。 Firebase 身份驗證可透過三種方式實現此目的:

  • Play Integrity API :如果使用者的裝置安裝了 Google Play 服務,且 Firebase 驗證可以使用Play Integrity API驗證該裝置是否合法,則可以繼續進行電話號碼登入。 Play Integrity API 是透過 Firebase 驗證在 Google 擁有的專案上啟用的,而不是在您的專案上啟用的。這不會影響您專案的任何 Play Integrity API 配額。身份驗證 SDK v21.2.0+ (Firebase BoM v31.4.0+) 提供 Play 完整性支援。

    若要使用 Play Integrity,如果您尚未指定要套用的 SHA-256 指紋,請從 Firebase 控制台的專案設定中執行此操作。有關如何取得應用程式的 SHA-256 指紋的詳細信息,請參閱驗證您的客戶端

  • reCAPTCHA 驗證:如果無法使用 Play Integrity,例如當使用者的裝置安裝 Google Play 服務時,Firebase 驗證將使用 reCAPTCHA 驗證來完成手機登入流程。 reCAPTCHA 挑戰通常可以在使用者無需解決任何問題的情況下完成。請注意,此流程要求 SHA-1 與您的應用程式關聯。此流程也要求您的 API 金鑰不受限製或列入PROJECT_ID .firebaseapp.com的白名單。

    觸發 reCAPTCHA 的一些場景:

    • 如果最終使用者的裝置未安裝 Google Play 服務。
    • 如果應用程式不是透過 Google Play 商店分發的(在Authentication SDK v21.2.0+上)。
    • 如果取得的 SafetyNet 令牌無效(在身分驗證 SDK 版本 < v21.2.0 上)。

    當使用 SafetyNet 或 Play Integrity 進行應用程式驗證時,SMS 範本中的%APP_NAME%欄位將填入從 Google Play 商店確定的應用程式名稱。在觸發 reCAPTCHA 的場景中, %APP_NAME%會填入PROJECT_ID .firebaseapp.com

您可以使用forceRecaptchaFlowForTesting強制執行reCAPTCHA驗證流程您可以使用setAppVerificationDisabledForTesting停用應用程式驗證(當使用虛構的電話號碼時)。

故障排除

  • 使用 reCAPTCHA 進行應用驗證時出現「缺少初始狀態」錯誤

    當 reCAPTCHA 流程成功完成但未將使用者重新導向回本機應用程式時,可能會發生這種情況。如果發生這種情況,使用者將被重新導向到後備 URL PROJECT_ID .firebaseapp.com/__/auth/handler 。在 Firefox 瀏覽器上,預設會停用開啟本機應用程式連結。如果您在 Firefox 上看到上述錯誤,請按照設定 Firefox for Android 在本機應用程式中開啟連結中的步驟啟用開啟應用程式連結。

發送驗證碼至用戶手機

若要啟動電話號碼登錄,請提供使用者一個提示他們輸入電話號碼的介面。法律要求各不相同,但作為最佳實踐並為用戶設定期望,您應該告知他們,如果他們使用電話登錄,他們可能會收到一條用於驗證的短信,並且適用標準費率。

然後,將其電話號碼傳遞給PhoneAuthProvider.verifyPhoneNumber方法,以請求 Firebase 驗證使用者的電話號碼。例如:

Kotlin+KTX

val options = PhoneAuthOptions.newBuilder(auth)
    .setPhoneNumber(phoneNumber) // Phone number to verify
    .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
    .setActivity(this) // Activity (for callback binding)
    .setCallbacks(callbacks) // OnVerificationStateChangedCallbacks
    .build()
PhoneAuthProvider.verifyPhoneNumber(options)

Java

PhoneAuthOptions options = 
  PhoneAuthOptions.newBuilder(mAuth) 
      .setPhoneNumber(phoneNumber)       // Phone number to verify
      .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
      .setActivity(this)                 // (optional) Activity for callback binding
      // If no activity is passed, reCAPTCHA verification can not be used.
      .setCallbacks(mCallbacks)          // OnVerificationStateChangedCallbacks
      .build();
  PhoneAuthProvider.verifyPhoneNumber(options);     

verifyPhoneNumber方法是可重入的:如果您多次呼叫它,例如在活動的onStart方法中,則verifyPhoneNumber方法將不會發送第二條短信,除非原始請求已逾時。

如果您的應用程式在使用者登入之前關閉(例如,當使用者正在使用其簡訊應用程式時),您可以使用此行為恢復電話號碼登入程序。呼叫verifyPhoneNumber後,設定一個標誌以指示驗證正在進行中。然後,在 Activity 的onSaveInstanceState方法中保存該標誌,並在onRestoreInstanceState中恢復該標誌。最後,在 Activity 的onStart方法中,檢查驗證是否已在進行中,如果是,請再次呼叫verifyPhoneNumber 。請務必在驗證完成或失敗時清除該標誌(請參閱驗證回呼)。

若要輕鬆處理螢幕旋轉和其他 Activity 重新啟動的實例,請將 Activity 傳遞給verifyPhoneNumber方法。當 Activity 停止時,回呼將自動分離,因此您可以在回呼方法中自由編寫 UI 轉換程式碼。

Firebase 傳送的 SMS 訊息也可以透過 Auth 實例上的setLanguageCode方法指定驗證語言來本地化。

Kotlin+KTX

auth.setLanguageCode("fr")
// To apply the default app language instead of explicitly setting it.
// auth.useAppLanguage()

Java

auth.setLanguageCode("fr");
// To apply the default app language instead of explicitly setting it.
// auth.useAppLanguage();

當您呼叫PhoneAuthProvider.verifyPhoneNumber時,您還必須提供OnVerificationStateChangedCallbacks的實例,其中包含處理請求結果的回調函數的實作。例如:

Kotlin+KTX

callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

    override fun onVerificationCompleted(credential: PhoneAuthCredential) {
        // This callback will be invoked in two situations:
        // 1 - Instant verification. In some cases the phone number can be instantly
        //     verified without needing to send or enter a verification code.
        // 2 - Auto-retrieval. On some devices Google Play services can automatically
        //     detect the incoming verification SMS and perform verification without
        //     user action.
        Log.d(TAG, "onVerificationCompleted:$credential")
        signInWithPhoneAuthCredential(credential)
    }

    override fun onVerificationFailed(e: FirebaseException) {
        // This callback is invoked in an invalid request for verification is made,
        // for instance if the the phone number format is not valid.
        Log.w(TAG, "onVerificationFailed", e)

        if (e is FirebaseAuthInvalidCredentialsException) {
            // Invalid request
        } else if (e is FirebaseTooManyRequestsException) {
            // The SMS quota for the project has been exceeded
        } else if (e is FirebaseAuthMissingActivityForRecaptchaException) {
            // reCAPTCHA verification attempted with null Activity
        }

        // Show a message and update the UI
    }

    override fun onCodeSent(
        verificationId: String,
        token: PhoneAuthProvider.ForceResendingToken,
    ) {
        // The SMS verification code has been sent to the provided phone number, we
        // now need to ask the user to enter the code and then construct a credential
        // by combining the code with a verification ID.
        Log.d(TAG, "onCodeSent:$verificationId")

        // Save verification ID and resending token so we can use them later
        storedVerificationId = verificationId
        resendToken = token
    }
}

Java

mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

    @Override
    public void onVerificationCompleted(@NonNull PhoneAuthCredential credential) {
        // This callback will be invoked in two situations:
        // 1 - Instant verification. In some cases the phone number can be instantly
        //     verified without needing to send or enter a verification code.
        // 2 - Auto-retrieval. On some devices Google Play services can automatically
        //     detect the incoming verification SMS and perform verification without
        //     user action.
        Log.d(TAG, "onVerificationCompleted:" + credential);

        signInWithPhoneAuthCredential(credential);
    }

    @Override
    public void onVerificationFailed(@NonNull FirebaseException e) {
        // This callback is invoked in an invalid request for verification is made,
        // for instance if the the phone number format is not valid.
        Log.w(TAG, "onVerificationFailed", e);

        if (e instanceof FirebaseAuthInvalidCredentialsException) {
            // Invalid request
        } else if (e instanceof FirebaseTooManyRequestsException) {
            // The SMS quota for the project has been exceeded
        } else if (e instanceof FirebaseAuthMissingActivityForRecaptchaException) {
            // reCAPTCHA verification attempted with null Activity
        }

        // Show a message and update the UI
    }

    @Override
    public void onCodeSent(@NonNull String verificationId,
                           @NonNull PhoneAuthProvider.ForceResendingToken token) {
        // The SMS verification code has been sent to the provided phone number, we
        // now need to ask the user to enter the code and then construct a credential
        // by combining the code with a verification ID.
        Log.d(TAG, "onCodeSent:" + verificationId);

        // Save verification ID and resending token so we can use them later
        mVerificationId = verificationId;
        mResendToken = token;
    }
};

驗證回調

在大多數應用程式中,您可以實作onVerificationCompletedonVerificationFailedonCodeSent回調。您也可以實作onCodeAutoRetrievalTimeOut ,具體取決於您的應用程式的要求。

onVerificationCompleted(電話驗證憑證)

該方法在兩種情況下被調用:

  • 即時驗證:在某些情況下,無需發送或輸入驗證碼即可立即驗證電話號碼。
  • 自動擷取:在某些裝置上,Google Play 服務可以自動偵測傳入的驗證簡訊並執行驗證,而無需使用者操作。 (某些運營商可能不提供此功能。)這使用SMS Retriever API ,其中在 SMS 訊息末尾包含 11 個字元的雜湊值。
無論哪種情況,使用者的電話號碼已成功驗證,您可以使用傳遞給回呼的PhoneAuthCredential物件來登入使用者

onVerificationFailed(FirebaseException)

此方法是為了回應無效的驗證請求而呼叫的,例如指定無效的電話號碼或驗證碼的請求。

onCodeSent(字串驗證Id, PhoneAuthProvider.ForceResendingToken)

選修的。透過簡訊將驗證碼發送到提供的電話號碼後,將呼叫此方法。

呼叫此方法時,大多數應用程式都會顯示一個 UI,提示使用者輸入簡訊中的驗證碼。 (同時,自動驗證可能會在背景進行。)然後,在使用者輸入驗證碼後,您可以使用驗證碼和傳遞給該方法的驗證ID來建立PhoneAuthCredential對象,您可以依序使用該使用者登入。但是,某些應用程式可能會等到呼叫onCodeAutoRetrievalTimeOut後才顯示驗證碼 UI(不建議)。

onCodeAutoRetrievalTimeOut(字串驗證ID)

選修的。在為verifyPhoneNumber指定的逾時持續時間過後且未先觸發onVerificationCompleted情況下呼叫此方法。在沒有 SIM 卡的裝置上,會立即呼叫此方法,因為無法自動擷取簡訊。

某些應用程式會阻止使用者輸入,直到自動驗證期限逾時,然後才顯示 UI 提示使用者輸入簡訊中的驗證碼(不建議)。

建立 PhoneAuthCredential 對象

使用者輸入 Firebase 傳送到使用者手機的驗證碼後,使用驗證碼和傳遞給onCodeSentonCodeAutoRetrievalTimeOut回呼的驗證 ID 建立PhoneAuthCredential物件。 (當呼叫onVerificationCompleted時,直接取得PhoneAuthCredential對象,所以可以跳過這一步。)

若要建立PhoneAuthCredential對象,請呼叫PhoneAuthProvider.getCredential

Kotlin+KTX

val credential = PhoneAuthProvider.getCredential(verificationId!!, code)

Java

PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);

登入用戶

取得PhoneAuthCredential物件後,無論是在onVerificationCompleted回呼中或是透過呼叫PhoneAuthProvider.getCredential ,都可以透過將PhoneAuthCredential物件傳遞給FirebaseAuth.signInWithCredential來完成登入流程:

Kotlin+KTX

private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) {
    auth.signInWithCredential(credential)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                // Sign in success, update UI with the signed-in user's information
                Log.d(TAG, "signInWithCredential:success")

                val user = task.result?.user
            } else {
                // Sign in failed, display a message and update the UI
                Log.w(TAG, "signInWithCredential:failure", task.exception)
                if (task.exception is FirebaseAuthInvalidCredentialsException) {
                    // The verification code entered was invalid
                }
                // Update UI
            }
        }
}

Java

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");

                        FirebaseUser user = task.getResult().getUser();
                        // Update UI
                    } else {
                        // Sign in failed, display a message and update the UI
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            // The verification code entered was invalid
                        }
                    }
                }
            });
}

使用虛構的電話號碼進行測試

您可以透過 Firebase 控制台設定用於開發的虛構電話號碼。使用虛構電話號碼進行測試具有以下優點:

  • 測試電話號碼身份驗證而不消耗您的使用配額。
  • 在不發送實際簡訊的情況下測試電話號碼身份驗證。
  • 使用相同的電話號碼執行連續測試而不會受到限制。如果審核者碰巧使用相同的電話號碼進行測試,這可以最大限度地降低應用程式商店審核過程中被拒絕的風險。
  • 無需任何額外工作即可在開發環境中輕鬆進行測試,例如無需 Google Play 服務即可在 iOS 模擬器或 Android 模擬器中進行開發。
  • 編寫整合測試,而不會被通常應用於生產環境中真實電話號碼的安全檢查所阻止。

虛構電話號碼必須符合以下要求:

  1. 確保您使用的電話號碼確實是虛構的且不存在。 Firebase 驗證不允許您將真實使用者使用的現有電話號碼設定為測試號碼。一種選擇是使用 555 前綴號碼作為美國測試電話號碼,例如: +1 650-555-3434
  2. 電話號碼的格式必須正確,以符合長度和其他限制。它們仍將經過與真實用戶電話號碼相同的驗證。
  3. 您最多可以新增 10 個電話號碼進行開發。
  4. 使用難以猜測的測試電話號碼/代碼並經常更改。

創建虛構的電話號碼和驗證碼

  1. Firebase 控制台中,開啟「驗證」部分。
  2. 登入方法標籤中,啟用電話提供者(如果尚未啟用)。
  3. 開啟用於測試手風琴選單的電話號碼
  4. 提供您要測試的電話號碼,例如: +1 650-555-3434
  5. 提供該特定號碼的 6 位驗證碼,例如: 654321
  6. 新增號碼。如果需要,您可以將滑鼠懸停在相應行上並點擊垃圾桶圖示來刪除電話號碼及其代碼。

手動測試

您可以直接在應用程式中開始使用虛構的電話號碼。這使您可以在開發階段執行手動測試,而不會遇到配額問題或限制。您也可以直接從 iOS 模擬器或 Android 模擬器進行測試,而無需安裝 Google Play 服務。

當您提供虛構的電話號碼並發送驗證碼時,不會發送實際的簡訊。相反,您需要提供先前配置的驗證碼才能完成登入。

登入完成後,系統會使用該電話號碼建立 Firebase 使用者。使用者俱有與真實電話號碼使用者相同的行為和屬性,並且可以以相同的方式存取即時資料庫/Cloud Firestore 和其他服務。在此過程中產生的 ID 令牌與真實電話號碼使用者俱有相同的簽名。

如果您想進一步限制訪問,另一種選擇是透過對這些用戶的自訂聲明設定測試角色,以將他們區分為假用戶。

若要手動觸發 reCAPTCHA 流程進行測試,請使用forceRecaptchaFlowForTesting()方法。

// Force reCAPTCHA flow
FirebaseAuth.getInstance().getFirebaseAuthSettings().forceRecaptchaFlowForTesting();

整合測試

除了手動測試之外,Firebase 驗證還提供 API 來協助編寫電話身份驗證測試的整合測試。這些 API 透過停用 Web 中的 reCAPTCHA 要求和 iOS 中的靜默推播通知來停用應用程式驗證。這使得這些流程中的自動化測試成為可能並且更容易實施。此外,它們還有助於提供在 Android 上測試即時驗證流程的能力。

在 Android 上,在signInWithPhoneNumber呼叫之前呼叫setAppVerificationDisabledForTesting() 。這會自動停用應用程式驗證,允許您傳遞電話號碼而無需手動解決。即使 Play Integrity 和 reCAPTCHA 被停用,使用真實的電話號碼仍然無法完成登入。此 API 只能使用虛構的電話號碼。

// Turn off phone auth app verification.
FirebaseAuth.getInstance().getFirebaseAuthSettings()
   .setAppVerificationDisabledForTesting();

使用虛構號碼呼叫verifyPhoneNumber會觸發onCodeSent回調,您需要在該回呼中提供對應的驗證碼。這允許在 Android 模擬器中進行測試。

Java

String phoneNum = "+16505554567";
String testVerificationCode = "123456";

// Whenever verification is triggered with the whitelisted number,
// provided it is not set for auto-retrieval, onCodeSent will be triggered.
FirebaseAuth auth = FirebaseAuth.getInstance();
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(auth)
        .setPhoneNumber(phoneNum)
        .setTimeout(60L, TimeUnit.SECONDS)
        .setActivity(this)
        .setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            @Override
            public void onCodeSent(@NonNull String verificationId,
                                   @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                // Save the verification id somewhere
                // ...

                // The corresponding whitelisted code above should be used to complete sign-in.
                MainActivity.this.enableUserManuallyInputCode();
            }

            @Override
            public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
                // Sign in with the credential
                // ...
            }

            @Override
            public void onVerificationFailed(@NonNull FirebaseException e) {
                // ...
            }
        })
        .build();
PhoneAuthProvider.verifyPhoneNumber(options);

Kotlin+KTX

val phoneNum = "+16505554567"
val testVerificationCode = "123456"

// Whenever verification is triggered with the whitelisted number,
// provided it is not set for auto-retrieval, onCodeSent will be triggered.
val options = PhoneAuthOptions.newBuilder(Firebase.auth)
    .setPhoneNumber(phoneNum)
    .setTimeout(30L, TimeUnit.SECONDS)
    .setActivity(this)
    .setCallbacks(object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

        override fun onCodeSent(
            verificationId: String,
            forceResendingToken: PhoneAuthProvider.ForceResendingToken,
        ) {
            // Save the verification id somewhere
            // ...

            // The corresponding whitelisted code above should be used to complete sign-in.
            this@MainActivity.enableUserManuallyInputCode()
        }

        override fun onVerificationCompleted(phoneAuthCredential: PhoneAuthCredential) {
            // Sign in with the credential
            // ...
        }

        override fun onVerificationFailed(e: FirebaseException) {
            // ...
        }
    })
    .build()
PhoneAuthProvider.verifyPhoneNumber(options)

此外,您也可以透過呼叫setAutoRetrievedSmsCodeForPhoneNumber設定虛構號碼及其對應的自動擷取驗證碼來測試 Android 中的自動擷取流程。

當呼叫verifyPhoneNumber時,它會直接使用PhoneAuthCredential觸發onVerificationCompleted 。這僅適用於虛構的電話號碼。

將應用程式發佈到 Google Play 商店時,請確保已停用此功能,並且應用程式中沒有硬編碼任何虛構的電話號碼。

Java

// The test phone number and code should be whitelisted in the console.
String phoneNumber = "+16505554567";
String smsCode = "123456";

FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseAuthSettings firebaseAuthSettings = firebaseAuth.getFirebaseAuthSettings();

// Configure faking the auto-retrieval with the whitelisted numbers.
firebaseAuthSettings.setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber, smsCode);

PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
        .setPhoneNumber(phoneNumber)
        .setTimeout(60L, TimeUnit.SECONDS)
        .setActivity(this)
        .setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            @Override
            public void onVerificationCompleted(@NonNull PhoneAuthCredential credential) {
                // Instant verification is applied and a credential is directly returned.
                // ...
            }

            // ...
        })
        .build();
PhoneAuthProvider.verifyPhoneNumber(options);

Kotlin+KTX

// The test phone number and code should be whitelisted in the console.
val phoneNumber = "+16505554567"
val smsCode = "123456"

val firebaseAuth = Firebase.auth
val firebaseAuthSettings = firebaseAuth.firebaseAuthSettings

// Configure faking the auto-retrieval with the whitelisted numbers.
firebaseAuthSettings.setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber, smsCode)

val options = PhoneAuthOptions.newBuilder(firebaseAuth)
    .setPhoneNumber(phoneNumber)
    .setTimeout(60L, TimeUnit.SECONDS)
    .setActivity(this)
    .setCallbacks(object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        override fun onVerificationCompleted(credential: PhoneAuthCredential) {
            // Instant verification is applied and a credential is directly returned.
            // ...
        }

        // ...
    })
    .build()
PhoneAuthProvider.verifyPhoneNumber(options)

下一步

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

  • 在您的應用程式中,您可以從FirebaseUser物件取得使用者的基本個人資料資訊。請參閱管理用戶

  • 在 Firebase 即時資料庫和雲端儲存安全性規則中,您可以從auth變數取得登入使用者的唯一使用者 ID,並使用它來控制使用者可以存取哪些資料。

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

若要登出用戶,請呼叫signOut

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();