您可以使用 Firebase 身份驗證來創建和使用臨時匿名帳戶來通過 Firebase 進行身份驗證。這些臨時匿名帳戶可用於允許尚未註冊您的應用的用戶使用受安全規則保護的數據。如果匿名用戶決定註冊您的應用程序,您可以將他們的登錄憑據鏈接到匿名帳戶,以便他們可以在以後的會話中繼續使用受保護的數據。
在你開始之前
- 如果您還沒有,請將 Firebase 添加到您的 Android 項目中。
- 使用Firebase Android BoM ,在模塊(應用級)Gradle 文件(通常是
app/build.gradle
)中聲明 Firebase Authentication Android 庫的依賴項。Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.2.0') // Declare 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 { // Declare 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:21.0.6' }
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.2.0') // Declare 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 { // Declare 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:21.0.6' }
- 如果您尚未將應用連接到 Firebase 項目,請從Firebase 控制台執行此操作。
- 啟用匿名身份驗證:
- 在Firebase 控制台中,打開Auth部分。
- 在登錄方法頁面上,啟用匿名登錄方法。
匿名使用 Firebase 進行身份驗證
當已註銷的用戶使用需要通過 Firebase 進行身份驗證的應用功能時,請完成以下步驟以匿名方式登錄該用戶:
- 在您的活動的
onCreate
方法中,獲取FirebaseAuth
對象的共享實例:Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
Kotlin+KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
- 初始化 Activity 時,檢查用戶當前是否登錄:
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); }
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) }
- 最後,調用
signInAnonymously
以匿名用戶身份登錄:如果登錄成功,您可以使用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); } } });
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) } }
getCurrentUser
方法獲取用戶的帳戶數據。
將匿名帳戶轉換為永久帳戶
當匿名用戶註冊您的應用程序時,您可能希望允許他們使用新帳戶繼續工作——例如,您可能希望讓用戶在註冊之前添加到購物車中的商品在他們的新帳戶中可用帳戶的購物車。為此,請完成以下步驟:
- 當用戶註冊時,完成用戶身份驗證提供程序的登錄流程,直至調用
FirebaseAuth.signInWith
方法之一,但不包括在內。例如,獲取用戶的 Google ID 令牌、Facebook 訪問令牌或電子郵件地址和密碼。 獲取新身份驗證提供程序的
AuthCredential
:谷歌登錄
Java
AuthCredential credential = GoogleAuthProvider.getCredential(googleIdToken, null);
Kotlin+KTX
val credential = GoogleAuthProvider.getCredential(googleIdToken, null)
Facebook登入
Java
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
Kotlin+KTX
val credential = FacebookAuthProvider.getCredential(token.token)
電子郵件密碼登錄
Java
AuthCredential credential = EmailAuthProvider.getCredential(email, password);
Kotlin+KTX
val credential = EmailAuthProvider.getCredential(email, password)
將
AuthCredential
對像傳遞給登錄用戶的linkWithCredential
方法: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); } } });
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) } }
如果對
linkWithCredential
的調用成功,則用戶的新帳戶可以訪問匿名帳戶的 Firebase 數據。下一步
現在用戶可以使用 Firebase 進行身份驗證,您可以使用Firebase 規則控制他們對 Firebase 數據庫中數據的訪問。
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2022-07-06 UTC.
[] []