在 Android 上使用電話號碼驗證 Firebase

您可以使用 Firebase 驗證功能傳送簡訊讓使用者登入 傳送到使用者的手機上使用者透過 簡訊。

如要在應用程式中新增電話號碼登入程序,最簡單的方法是使用 FirebaseUI, 包含用於實作手機登入流程的置入登入小工具 以及密碼和聯合登入。這份文件 說明如何使用 Firebase SDK 導入電話號碼登入流程。

事前準備

  1. 如果還沒試過 將 Firebase 新增至您的 Android 專案
  2. 模組 (應用程式層級) Gradle 檔案中 (通常為 <project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle)、 新增 Android 版 Firebase 驗證程式庫的依附元件。建議您使用 Firebase Android BoM 管理程式庫版本管理
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.1.2"))
    
        // 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 程式庫版本。

    (替代做法) 新增 Firebase 程式庫依附元件,「不使用」BoM

    如果選擇不使用 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:23.0.0")
    }
    
    在尋找 Kotlin 專用的程式庫模組嗎?距離開始還有 2023 年 10 月 (Firebase BoM 32.5.0),Kotlin 和 Java 開發人員都能 依附於主要程式庫模組 (詳情請參閱 這項計畫的常見問題)。
  3. 如果您尚未將應用程式連結至 Firebase 專案,請前往 Firebase 控制台
  4. 如果您尚未在 Firebase 控制台設定應用程式的 SHA-1 雜湊, 。詳情請參閱「」 驗證用戶端以找出應用程式的 SHA-1 雜湊值。

安全疑慮

僅使用電話號碼進行驗證,安全性較低 其他可用的方法,因為擁有電話號碼 可以在使用者之間輕鬆轉移此外,當多位使用者共用裝置時 設定檔,任何可接收簡訊的使用者,皆可透過 裝置的電話號碼。

如果您在應用程式中使用電話號碼登入功能,則應提供這項功能 提供更安全的登入方式,並告知使用者這項安全措施 也不必為了使用電話號碼登入而做出取捨

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

您必須先啟用電話號碼登入功能,才能透過簡訊登入使用者 方法:

  1. Firebase 控制台開啟「驗證」專區。
  2. 在「Sign-in Method」(登入方式) 頁面中啟用電話號碼 登入方式。

Firebase 的電話號碼登入要求配額夠高,適用於大多數應用程式 不會受到影響但如果需要登入大量使用者 電話驗證,你可能需要升級定價方案。詳情請見 請參閱定價頁面。

啟用應用程式驗證功能

如要使用電話號碼驗證功能,Firebase 必須能夠驗證 電話號碼登入要求來自您的應用程式。與 GCP 互動的方式 Firebase 驗證功能會完成這項動作:

  • Play Integrity API:如果使用者的裝置已安裝 Google Play 服務, 並使用 Firebase 驗證功能 Play Integrity API, 登入電話號碼才能繼續操作。已透過以下方式在 Google 自有專案中啟用 Play Integrity API: Firebase 驗證,不是您的專案。這不會影響任何 Play Integrity API 設定專案配額Play Integrity 目前由 Authentication SDK 21.2.0 以上版本 (Firebase BoM v31.4.0 以上版本)。

    如果您尚未指定應用程式的 SHA-256 指紋,請使用 Play Integrity 從 專案 設定。詳情請參閱 驗證您的 用戶端,進一步瞭解如何取得應用程式的 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 權杖無效 (在 Authentication SDK 版本 < 21.2.0 中) 無效,

    使用 SafetyNet 或 Play Integrity 進行應用程式驗證時,簡訊範本的 %APP_NAME% 欄位會填入從 Google Play 商店判定的應用程式名稱。 在觸發 reCAPTCHA 的情況下,系統會將 %APP_NAME% 填入 PROJECT_ID.firebaseapp.com

您可以運用下列方法強制執行 reCAPTCHA 驗證流程: forceRecaptchaFlowForTesting 使用虛構電話號碼時,您可以停用應用程式驗證功能,方法是使用 setAppVerificationDisabledForTesting

疑難排解

  • 「缺少初始狀態」使用 reCAPTCHA 驗證應用程式時發生錯誤

    當 reCAPTCHA 流程成功完成,但並未將使用者重新導向回原生應用程式,就可能會發生這種情況。在這種情況下,系統會將使用者重新導向至備用網址 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 後,請設定旗標 表示驗證進行中。然後將該旗標儲存在活動的 onSaveInstanceState 方法,並將旗標還原到 onRestoreInstanceState。最後,在活動的 onStart 方法,檢查是否已進行驗證,並且 如果有,請再次呼叫 verifyPhoneNumber。如要清除標記,請務必清除標記 驗證完成或失敗 (請參閱 驗證回呼)。

如要輕鬆處理螢幕旋轉和其他活動重新啟動情形, 將活動傳遞至 verifyPhoneNumber 方法。回呼 活動停止時會自動卸離,因此您可以自由編寫 UI 轉換程式碼。

您也能指定 Firebase 傳送的簡訊, 透過驗證上的 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(PhoneAuthCredential)

系統會在兩種情況下呼叫此方法:

  • 即時驗證:在部分情況下,電話號碼可立即更新 而且不需傳送或輸入驗證碼。
  • 自動擷取:在部分裝置上,Google Play 服務可以 自動偵測收到的驗證簡訊,然後執行 不必使用者操作就能驗證(這項功能可能無法使用 部分電信業者)。這會使用 SMS Retriever API: 會在簡訊結尾加上 11 個字元的雜湊。
不論是哪一種情況,使用者的電話號碼都已經通過驗證,且 您可以使用傳遞給PhoneAuthCredential 登入使用者的回呼。

onVerificationFailed(FirebaseException)

為回應無效的驗證要求,系統會呼叫此方法, 視為指定無效電話號碼或驗證碼的要求。

onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken)

選用設定。驗證碼傳送後,系統會呼叫此方法 透過簡訊傳送至所提供的電話號碼。

呼叫此方法時,大多數應用程式都會顯示提示使用者的 UI 輸入簡訊中的驗證碼。(與此同時, 自動驗證可能會在背景繼續進行)。接著,在使用者之後 輸入驗證碼,您可以使用這組驗證碼 傳遞到用於建立 PhoneAuthCredential 物件,可以接著用來登入 使用者。不過,有些應用程式 系統會在顯示onCodeAutoRetrievalTimeOut 驗證碼使用者介面 (不建議)。

onCodeAutoRetrievalTimeOut(String verificationId)

選用設定。系統會在為以下時間指定的逾時期限過後呼叫此方法 verifyPhoneNumber 已過,但未使用 onVerificationCompleted會先觸發。在未安裝 SIM 卡的裝置上 卡,此方法會立即呼叫,因為系統不會自動擷取簡訊

部分應用程式會阻止使用者輸入內容,直到自動驗證期限逾時。 然後只顯示提示使用者輸入驗證碼的使用者介面 讀取訊息 (不建議)。

建立 PhoneAuthCredential 物件

使用者輸入 Firebase 傳送至使用者的驗證碼後 電話,請使用驗證步驟建立 PhoneAuthCredential 物件 驗證碼和傳遞至 onCodeSent 的驗證 ID onCodeAutoRetrievalTimeOut 回呼。(時間 已呼叫 onVerificationCompletedPhoneAuthCredential 物件,因此可略過這個步驟)。

如要建立 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 組前置字元為美國的測試電話號碼,例如: 0933 000 000
  2. 電話號碼的格式必須正確, 限制。不過,他們仍須完成與實際使用者電話號碼相同的驗證。
  3. 您最多可以新增 10 組開發用電話號碼。
  4. 使用不易猜到和變更的測試電話號碼/驗證碼 經常更新

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

  1. Firebase 控制台,開啟 「Authentication」區段。
  2. 在「登入方式」分頁中啟用電話服務供應商 (如果您尚未啟用的話)。
  3. 開啟「測試用電話號碼」選單。
  4. 提供要測試的電話號碼,例如 +1 650-555-3434
  5. 提供該特定號碼的 6 位數驗證碼,例如「654321」
  6. 新增數字。如有需要,你可以刪除電話號碼,以及 請將滑鼠遊標懸停在對應資料列上,再按一下垃圾桶圖示。

手動測試

您可以直接開始在應用程式中使用虛構的電話號碼。您可以藉此 執行手動測試,而不會發生配額問題或節流問題。 您也可以使用沒有 Google Play 服務的 iOS 模擬器或 Android 模擬器直接進行測試 已安裝。

如果您提供虛構的電話號碼並傳送驗證碼,則簡訊不會是 已傳送。您需要提供先前設定的驗證碼,才能完成簽署。 。

登入完成後,系統會使用該電話號碼建立 Firebase 使用者。 使用者和實際電話號碼使用者俱有相同的行為和屬性, 即時資料庫/Cloud Firestore 和其他服務的使用方式相同。建立期間建立的 ID 符記 這項程序與實際電話號碼使用者擁有相同的簽章。

另一種方式是透過自訂角色設定測試角色 聲明,以便區分他們為冒用使用者,以便進一步限制 資源存取權

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

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

整合測試

除了手動測試外,Firebase 驗證也提供 API 協助您撰寫整合測試 用於手機驗證測試這些 API 會停用 reCAPTCHA 來停用應用程式驗證功能 以及 iOS 的靜音推播通知這樣就能在自動化環境中執行自動化測試 也能輕鬆實作也用來測試 驗證流程

在 Android 上,請在setAppVerificationDisabledForTesting() signInWithPhoneNumber 呼叫。這樣系統就會自動停用應用程式驗證功能。 可讓你傳遞電話號碼,不必手動解決。雖然 Play Integrity 和 reCAPTCHA 已停用,使用實際電話號碼仍會失敗 完成登入。這個 API 只能使用虛構的電話號碼。

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

使用虛構號碼呼叫 verifyPhoneNumber 會觸發 onCodeSent 回呼,其中需要提供對應的驗證 再也不是件繁重乏味的工作這可讓您在 Android Emulator 中進行測試。

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)

此外,您可以設定虛構的數字,在 Android 中測試自動擷取流程 並呼叫 setAutoRetrievedSmsCodeForPhoneNumber

verifyPhoneNumber為 ,此方法會使用 PhoneAuthCredential 觸發 onVerificationCompleted 此功能只適用於虛構的電話號碼。

請確認已停用此設定,且沒有以硬式編碼方式寫入虛構電話號碼 。

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 即時資料庫和 Cloud Storage 中 查看安全性規則即可 透過 auth 變數取得已登入使用者的不重複使用者 ID。 控管使用者可以存取的資料

您可以讓使用者透過多重驗證機制登入您的應用程式 將驗證供應商憑證連結至 現有的使用者帳戶

如要登出使用者,請呼叫 signOut

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();