Catch up on highlights from Firebase at Google I/O 2023. Learn more

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

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

在你開始之前

  1. 如果您還沒有,請將 Firebase 添加到您的 Android 項目中
  2. 在您的模塊(應用級)Gradle 文件(通常為<project>/<app-module>/build.gradle )中,添加 Firebase 身份驗證 Android 庫的依賴項。我們建議使用Firebase Android BoM來控制庫版本。

    Kotlin+KTX

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

    Java

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.0')
    
        // 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.0.0'
    }
    
  3. 如果您尚未將您的應用程序連接到您的 Firebase 項目,請從Firebase 控制台執行此操作。
  4. 啟用匿名身份驗證:
    1. Firebase 控制台中,打開Auth部分。
    2. 登錄方法頁面上,啟用匿名登錄方法。
    3. 可選:如果您已將項目升級到Firebase Authentication with Identity Platform ,則可以啟用自動清理。當您啟用此設置時,超過 30 天的匿名帳戶將被自動刪除。在啟用了自動清理的項目中,匿名身份驗證將不再計入使用限製或計費配額。請參閱自動清理

匿名使用 Firebase 進行身份驗證

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

  1. 在您活動的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 天后自動刪除。
  • 如果您關閉自動清理,任何計劃刪除的匿名帳戶將保持計劃刪除。這些帳戶不計入使用限製或計費配額。
  • 如果您通過將匿名帳戶鏈接到任何登錄方法來“升級”該帳戶,該帳戶將不會被自動刪除。

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

下一步

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