您可以使用 Firebase 驗證讓您的使用者使用其電子郵件地址和密碼透過 Firebase 進行身份驗證,並管理您套用的基於密碼的帳戶。
在你開始之前
如果您尚未將 Firebase 新增至您的 Android 專案中,請將其新增至您的 Android 專案中。
- 如果您尚未將應用程式連線至 Firebase 項目,請從Firebase 控制台執行此操作。
- 啟用電子郵件/密碼登入:
- 在Firebase 控制台中,開啟「驗證」部分。
- 在登入方法標籤上,啟用電子郵件/密碼登入方法,然後按一下儲存。
在模組(應用程式層級)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") }
建立基於密碼的帳戶
若要建立具有密碼的新使用者帳戶,請在應用程式的登入活動中完成以下步驟:
- 在註冊活動的
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 即時資料庫和雲端儲存安全性規則中,您可以從
auth
變數取得登入使用者的唯一使用者 ID,並使用它來控制使用者可以存取哪些資料。
您可以透過將身分驗證提供者憑證連結到現有使用者帳戶,允許使用者使用多個驗證提供者登入您的應用程式。
若要登出用戶,請呼叫signOut
:
Kotlin+KTX
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();