您可以使用 Firebase Authentication 建立及使用臨時匿名帳戶,向 Firebase 驗證身分。這些臨時匿名帳戶可供尚未註冊應用程式的使用者,處理受安全性規則保護的資料。如果匿名使用者決定註冊應用程式,您可以將登入憑證連結至匿名帳戶,讓他們在日後的工作階段中繼續使用受保護的資料。
事前準備
- 如果您尚未將 Firebase 新增至 Android 專案,請先新增。
-
在模組 (應用程式層級) Gradle 檔案 (通常是
<project>/<app-module>/build.gradle.kts
或<project>/<app-module>/build.gradle
) 中,加入 Android 適用的 Firebase Authentication 程式庫依附元件。建議使用 Firebase Android BoM 控制程式庫版本。dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.0.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:24.0.0") }
- 如果尚未將應用程式連結至 Firebase 專案,請從 Firebase 控制台進行連結。
- 啟用匿名驗證:
- 在 Firebase 控制台中,開啟「Auth」(驗證) 部分。
- 在「登入方式」頁面中,啟用「匿名」登入方式。
- 選用:如果已將專案升級至 Firebase Authentication with Identity Platform,可以啟用自動清除功能。啟用這項設定後,系統就會自動刪除建立至今超過 30 天的匿名帳戶。在啟用自動清除功能的專案中,匿名驗證將不再計入用量限制或計費配額。請參閱「自動清除」一節。
以匿名方式向 Firebase 進行驗證
如果使用者登出後使用需要透過 Firebase 驗證身分的應用程式功能,請完成下列步驟,以匿名方式登入使用者:
- 在活動的
onCreate
方法中,取得FirebaseAuth
物件的共用例項:Kotlin
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
- 初始化 Activity 時,請檢查使用者目前是否已登入:
Kotlin
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); }
- 最後,呼叫
signInAnonymously
以匿名使用者身分登入:Kotlin
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
方法取得使用者帳戶資料。
將匿名帳戶轉換為永久帳戶
當匿名使用者註冊應用程式時,您可能希望允許他們使用新帳戶繼續工作,例如,您可能希望讓使用者在註冊前加入購物車的商品,在新帳戶的購物車中也能使用。如要這樣做,請完成下列步驟:
- 使用者註冊時,請完成使用者驗證供應商的登入流程,但不要呼叫
FirebaseAuth.signInWith
方法。例如,取得使用者的 Google ID 權杖、Facebook 存取權杖,或是電子郵件地址和密碼。 取得新驗證供應商的
AuthCredential
:Google 登入
Kotlin
val credential = GoogleAuthProvider.getCredential(googleIdToken, null)
Java
AuthCredential credential = GoogleAuthProvider.getCredential(googleIdToken, null);
Facebook 登入
Kotlin
val credential = FacebookAuthProvider.getCredential(token.token)
Java
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
使用電子郵件地址和密碼登入
Kotlin
val credential = EmailAuthProvider.getCredential(email, password)
Java
AuthCredential credential = EmailAuthProvider.getCredential(email, password);
將
AuthCredential
物件傳遞至登入使用者的linkWithCredential
方法:Kotlin
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 資料庫中資料的存取權。