在 Android 上使用 Firebase 進行匿名驗證

您可以使用 Firebase 身份驗證創建並使用臨時匿名帳戶來通過 Firebase 進行身份驗證。這些臨時匿名帳戶可用於允許尚未註冊您的應用程序的用戶使用受安全規則保護的數據。如果匿名用戶決定註冊您的應用程序,您可以將他們的登錄憑據鏈接到匿名帳戶,以便他們可以在將來的會話中繼續使用受保護的數據。

在你開始之前

  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. 啟用匿名身份驗證:
    1. Firebase 控制台中,打開“身份驗證”部分。
    2. 登錄方法頁面上,啟用匿名登錄方法。
    3. 可選:如果您已將項目升級到帶有 Identity Platform 的 Firebase 身份驗證,則可以啟用自動清理。啟用此設置後,超過 30 天的匿名帳戶將被自動刪除。在啟用自動清理的項目中,匿名身份驗證將不再計入使用限製或計費配額。請參閱自動清理

使用 Firebase 進行匿名身份驗證

當已註銷的用戶使用需要 Firebase 身份驗證的應用功能時,請通過完成以下步驟以匿名方式登錄用戶:

  1. 在您的 Activity 的onCreate方法中,獲取FirebaseAuth對象的共享實例:

    Kotlin+KTX

    private lateinit var auth: FirebaseAuth
    // ...
    // Initialize Firebase Auth
    auth = Firebase.auth

    Java

    private FirebaseAuth mAuth;
    // ...
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  2. 初始化您的 Activity 時,檢查用戶當前是否已登錄:

    Kotlin+KTX

    public override fun onStart() {
        super.onStart()
        // Check if user is signed in (non-null) and update UI accordingly.
        val currentUser = auth.currentUser
        updateUI(currentUser)
    }

    Java

    @Override
    public void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        updateUI(currentUser);
    }
  3. 最後,調用signInAnonymously以匿名用戶身份登錄:

    Kotlin+KTX

    auth.signInAnonymously()
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                // Sign in success, update UI with the signed-in user's information
                Log.d(TAG, "signInAnonymously:success")
                val user = auth.currentUser
                updateUI(user)
            } else {
                // If sign in fails, display a message to the user.
                Log.w(TAG, "signInAnonymously:failure", task.exception)
                Toast.makeText(
                    baseContext,
                    "Authentication failed.",
                    Toast.LENGTH_SHORT,
                ).show()
                updateUI(null)
            }
        }

    Java

    mAuth.signInAnonymously()
            .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, "signInAnonymously:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInAnonymously:failure", task.getException());
                        Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        updateUI(null);
                    }
                }
            });
    如果登錄成功,您可以使用getCurrentUser方法獲取用戶的帳戶數據。

將匿名帳戶轉換為永久帳戶

當匿名用戶註冊您的應用程序時,您可能希望允許他們使用新帳戶繼續工作 - 例如,您可能希望讓用戶在註冊之前添加到購物車的商品在他們的新帳戶中可用帳戶的購物車。為此,請完成以下步驟:

  1. 當用戶註冊時,完成用戶身份驗證提供程序的登錄流程,直至(但不包括)調用FirebaseAuth.signInWith方法之一。例如,獲取用戶的 Google ID 令牌、Facebook 訪問令牌或電子郵件地址和密碼。
  2. 獲取新身份驗證提供程序的AuthCredential

    谷歌登錄

    Kotlin+KTX

    val credential = GoogleAuthProvider.getCredential(googleIdToken, null)

    Java

    AuthCredential credential = GoogleAuthProvider.getCredential(googleIdToken, null);
    Facebook登入

    Kotlin+KTX

    val credential = FacebookAuthProvider.getCredential(token.token)

    Java

    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
    郵箱密碼登錄

    Kotlin+KTX

    val credential = EmailAuthProvider.getCredential(email, password)

    Java

    AuthCredential credential = EmailAuthProvider.getCredential(email, password);
  3. AuthCredential對像傳遞給登錄用戶的linkWithCredential方法:

    Kotlin+KTX

    auth.currentUser!!.linkWithCredential(credential)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                Log.d(TAG, "linkWithCredential:success")
                val user = task.result?.user
                updateUI(user)
            } else {
                Log.w(TAG, "linkWithCredential:failure", task.exception)
                Toast.makeText(
                    baseContext,
                    "Authentication failed.",
                    Toast.LENGTH_SHORT,
                ).show()
                updateUI(null)
            }
        }

    Java

    mAuth.getCurrentUser().linkWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "linkWithCredential:success");
                        FirebaseUser user = task.getResult().getUser();
                        updateUI(user);
                    } else {
                        Log.w(TAG, "linkWithCredential:failure", task.getException());
                        Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        updateUI(null);
                    }
                }
            });

如果對linkWithCredential的調用成功,則用戶的新帳戶可以訪問匿名帳戶的 Firebase 數據。

自動清理

如果您已將項目升級到Firebase Authentication with Identity Platform ,則可以在 Firebase 控制台中啟用自動清理。啟用此功能後,您允許 Firebase 自動刪除超過 30 天的匿名帳戶。在啟用自動清理的項目中,匿名身份驗證將不計入使用限製或計費配額。

  • 啟用自動清理後創建的任何匿名帳戶可能會在創建後 30 天后隨時自動刪除。
  • 啟用自動清理之前創建的匿名帳戶將在啟用自動清理後 30 天后符合自動刪除資格。
  • 如果您關閉自動清理,任何計劃刪除的匿名帳戶仍將保留計劃刪除。這些帳戶不計入使用限製或計費配額。
  • 如果您通過將匿名帳戶鏈接到任何登錄方法來“升級”該帳戶,則該帳戶不會被自動刪除。

如果您想在啟用此功能之前了解有多少用戶會受到影響,並且您已將項目升級到使用 Identity Platform 進行 Firebase 身份驗證,則可以在Cloud Logging中按is_anon進行過濾。

下一步

現在,用戶可以通過 Firebase 進行身份驗證,您可以使用Firebase 規則控制他們對 Firebase 數據庫中數據的訪問。