使用電話號碼在 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 身份驗證的依賴項安卓庫。我們建議使用Firebase Android BoM來控制庫版本控制。

    Kotlin+KTX

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.3.1"))
    
        // 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-ktx")
    }
    

    通過使用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-ktx:22.1.2")
    }
    

    Java

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.3.1"))
    
        // 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.1.2")
    }
    
  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();