您可以使用 Firebase 身份驗證讓您的用戶使用他們的電子郵件地址和密碼通過 Firebase 進行身份驗證,並管理您應用的基於密碼的帳戶。
在你開始之前
如果您還沒有,請將 Firebase 添加到您的 Android 項目中。
- 如果您尚未將您的應用程序連接到您的 Firebase 項目,請從Firebase 控制台執行此操作。
- 啟用電子郵件/密碼登錄:
- 在Firebase 控制台中,打開Auth部分。
- 在登錄方法選項卡上,啟用電子郵件/密碼登錄方法並單擊保存。
在您的模塊(應用級)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' }
創建基於密碼的帳戶
要創建一個帶密碼的新用戶帳戶,請在您應用的登錄活動中完成以下步驟:
- 在註冊活動的
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 if (currentUser != null) { reload() } }
Java
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); if(currentUser != null){ reload(); } }
- 當新用戶使用您應用的註冊表單註冊時,請完成您的應用所需的所有新帳戶驗證步驟,例如驗證新帳戶的密碼是否輸入正確並滿足您的複雜性要求。
- 通過將新用戶的電子郵件地址和密碼傳遞給
createUserWithEmailAndPassword
來創建一個新帳戶:如果創建了新賬戶,則用戶也已登錄。在回調中,您可以使用Kotlin+KTX
auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "createUserWithEmail:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.exception) Toast.makeText( baseContext, "Authentication failed.", Toast.LENGTH_SHORT, ).show() updateUI(null) } }
Java
mAuth.createUserWithEmailAndPassword(email, password) .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, "createUserWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.getException()); Toast.makeText(EmailPasswordActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } });
getCurrentUser
方法獲取用戶的賬戶數據。
使用電子郵件地址和密碼登錄用戶
使用密碼登錄用戶的步驟與創建新帳戶的步驟類似。在您應用的登錄活動中,執行以下操作:
- 在登錄活動的
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 if (currentUser != null) { reload() } }
Java
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); if(currentUser != null){ reload(); } }
- 當用戶登錄您的應用程序時,將用戶的電子郵件地址和密碼傳遞給
signInWithEmailAndPassword
:如果登錄成功,您可以使用返回的Kotlin+KTX
auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithEmail:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.exception) Toast.makeText( baseContext, "Authentication failed.", Toast.LENGTH_SHORT, ).show() updateUI(null) } }
Java
mAuth.signInWithEmailAndPassword(email, password) .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, "signInWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.getException()); Toast.makeText(EmailPasswordActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } });
FirebaseUser
繼續。
推薦:啟用電子郵件枚舉保護
如果電子郵件地址在必須註冊時未註冊(例如,使用電子郵件地址和密碼登錄時),或者在必須不使用時註冊(例如,更改用戶的電子郵件地址時)。雖然這有助於向用戶建議具體的補救措施,但它也可能被惡意行為者濫用以發現用戶註冊的電子郵件地址。
為降低此風險,我們建議您使用 Google Cloud gcloud
工具為您的項目啟用電子郵件枚舉保護。請注意,啟用此功能會更改 Firebase 身份驗證的錯誤報告行為:確保您的應用不依賴於更具體的錯誤。
下一步
用戶首次登錄後,將創建一個新的用戶帳戶並將其鏈接到用戶登錄所用的憑據,即用戶名和密碼、電話號碼或身份驗證提供商信息。這個新帳戶存儲為您的 Firebase 項目的一部分,可用於在項目中的每個應用程序中識別用戶,無論用戶如何登錄。
在您的應用中,您可以從
FirebaseUser
對象獲取用戶的基本個人資料信息。請參閱管理用戶。在您的 Firebase Realtime Database 和 Cloud Storage Security Rules中,您可以從
auth
變量中獲取登錄用戶的唯一用戶 ID,並使用它來控制用戶可以訪問哪些數據。
您可以允許用戶使用多個身份驗證提供程序登錄您的應用程序,方法是將身份驗證提供程序憑據鏈接到現有用戶帳戶。
要註銷用戶,請調用signOut
:
Kotlin+KTX
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();