您可以使用 Firebase 身份驗證讓您的用戶使用他們的電子郵件地址和密碼通過 Firebase 進行身份驗證,並管理您應用的基於密碼的帳戶。
在你開始之前
如果您還沒有,請將 Firebase 添加到您的 Android 項目中。
- 如果您尚未將應用連接到 Firebase 項目,請從Firebase 控制台執行此操作。
- 啟用電子郵件/密碼登錄:
- 在Firebase 控制台中,打開Auth部分。
- 在登錄方法選項卡上,啟用電子郵件/密碼登錄方法,然後單擊保存。
使用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.0.2') // 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.4' }
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.0.2') // 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.4' }
創建基於密碼的帳戶
要使用密碼創建新用戶帳戶,請在應用的登錄活動中完成以下步驟:
- 在您的註冊活動的
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(); if(currentUser != null){ reload(); } }
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(); } }
- 當新用戶使用您的應用程序的註冊表單進行註冊時,請完成您的應用程序所需的任何新帳戶驗證步驟,例如驗證新帳戶的密碼是否正確輸入並滿足您的複雜性要求。
- 通過將新用戶的電子郵件地址和密碼傳遞給
createUserWithEmailAndPassword
來創建一個新帳戶:如果創建了新帳戶,則用戶也已登錄。在回調中,您可以使用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); } } });
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) } }
getCurrentUser
方法獲取用戶的帳戶數據。
使用電子郵件地址和密碼登錄用戶
使用密碼登錄用戶的步驟與創建新帳戶的步驟類似。在您應用的登錄活動中,執行以下操作:
- 在您的登錄活動的
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(); if(currentUser != null){ reload(); } }
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(); } }
- 當用戶登錄您的應用時,將用戶的電子郵件地址和密碼傳遞給
signInWithEmailAndPassword
:如果登錄成功,您可以使用返回的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); } } });
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) } }
FirebaseUser
繼續。
下一步
用戶首次登錄後,會創建一個新用戶帳戶並將其鏈接到憑據(即用戶名和密碼、電話號碼或身份驗證提供商信息),即用戶登錄時使用的憑據。這個新帳戶作為 Firebase 項目的一部分存儲,可用於在項目中的每個應用中識別用戶,無論用戶如何登錄。
在您的應用中,您可以從
FirebaseUser
對象獲取用戶的基本個人資料信息。請參閱管理用戶。在您的 Firebase 實時數據庫和雲存儲安全規則中,您可以從
auth
變量中獲取登錄用戶的唯一用戶 ID,並使用它來控制用戶可以訪問哪些數據。
您可以通過將身份驗證提供程序憑據鏈接到現有用戶帳戶來允許用戶使用多個身份驗證提供程序登錄您的應用程序。
要註銷用戶,請調用signOut
:
Java
FirebaseAuth.getInstance().signOut();
Kotlin+KTX
Firebase.auth.signOut()