您可以使用 Firebase 驗證建立並使用臨時匿名帳戶來透過 Firebase 進行驗證。這些臨時匿名帳戶可用於允許尚未註冊您的應用程式的使用者使用受安全規則保護的資料。如果匿名使用者決定註冊您的應用程序,您可以將他們的登入憑證連結到匿名帳戶,以便他們可以在將來的會話中繼續使用受保護的資料。
在你開始之前
- 如果您尚未將 Firebase 新增至您的 Android 專案中,請將其新增至您的 Android 專案中。
- 在模組(應用程式層級)Gradle 檔案(通常
<project>/<app-module>/build.gradle.kts
或<project>/<app-module>/build.gradle
)中,新增Firebase 驗證的依賴項Android 的庫。我們建議使用Firebase Android BoM來控制函式庫版本控制。dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:32.6.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 程式庫的相容版本。
正在尋找 Kotlin 特定的庫模組?從2023 年 10 月(Firebase BoM 32.5.0)開始,Kotlin 和 Java 開發人員都可以依賴主庫模組(有關詳細信息,請參閱有關此計劃的常見問題解答)。(替代方法)在不使用 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.3.0") }
- 如果您尚未將應用程式連線至 Firebase 項目,請從Firebase 控制台執行此操作。
- 啟用匿名身份驗證:
- 在Firebase 控制台中,開啟「驗證」部分。
- 在登入方法頁面上,啟用匿名登入方法。
- 可選:如果您已將專案升級至具有 Identity Platform 的 Firebase 驗證,則可以啟用自動清理。啟用此設定後,超過 30 天的匿名帳戶將自動刪除。在啟用自動清理的項目中,匿名身分驗證將不再計入使用限製或計費配額。請參閱自動清理。
使用 Firebase 進行匿名身份驗證
當已登出的使用者使用需要 Firebase 驗證的應用程式功能時,請透過完成以下步驟以匿名方式登入使用者:
- 在您的 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();
- 初始化您的 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); }
- 最後,呼叫
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
方法來取得使用者的帳戶資料。
將匿名帳戶轉換為永久帳戶
當匿名用戶註冊您的應用程式時,您可能希望允許他們使用新帳戶繼續工作 - 例如,您可能希望讓用戶在註冊之前添加到購物車的商品在他們的新帳戶中可用帳戶的購物車。為此,請完成以下步驟:
- 當使用者註冊時,完成使用者驗證提供者的登入流程,直到(但不包括)呼叫
FirebaseAuth.signInWith
方法之一。例如,取得使用者的 Google ID 令牌、Facebook 存取權令牌或電子郵件地址和密碼。 取得新身分驗證提供者的
AuthCredential
:Google登入
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);
將
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 資料庫中資料的存取。