您可以使用 Firebase 驗證,讓使用者利用自己的電子郵件地址和密碼進行 Firebase 驗證,並管理應用程式的密碼型帳戶。
事前準備
如果您尚未將 Firebase 新增至 Android 專案,請先完成這項作業。
- 如果您尚未將應用程式連結至 Firebase 專案,請在 Firebase 控制台中進行設定。
- 啟用電子郵件/密碼登入功能:
- 在 Firebase 控制台,開啟「驗證」專區。
- 在「Sign in method」分頁中,啟用「Email/password」登入方式,然後按一下「Save」。
在模組 (應用程式層級) Gradle 檔案 (通常是
<project>/<app-module>/build.gradle.kts
或<project>/<app-module>/build.gradle
) 中,新增 Android 適用的 Firebase 驗證程式庫的依附元件。建議您使用 Firebase Android BoM 來控管程式庫版本管理。dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.1.1")) // 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 程式庫版本。
(替代方法) 新增 Firebase 程式庫依附元件,「不必」使用 BoM
如果選擇不使用 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:23.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();
- 初始化活動時,請檢查使用者是否已登入:
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();
- 初始化活動時,請檢查使用者是否已登入:
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
繼續操作。
建議:啟用電子郵件列舉防護功能
在必須註冊電子郵件地址的情況下 (例如使用電子郵件地址和密碼登入時),有些 Firebase 驗證方法會擲回特定錯誤,或是在必須無法使用的情況下 (例如變更使用者的電子郵件地址) 註冊時,就會擲回特定的錯誤。雖然這對於向使用者建議特定解決方法很有用,但惡意人士也可能會濫用這些手段,找出使用者註冊的電子郵件地址。
為降低這種風險,建議您使用 Google Cloud gcloud
工具,為專案啟用電子郵件列舉防護功能。請注意,啟用這項功能會變更 Firebase 驗證的錯誤回報行為:請確保應用程式不依賴更具體的錯誤。
後續步驟
使用者首次登入後,系統會建立新的使用者帳戶,並連結至用來登入的使用者憑證,也就是使用者名稱與密碼、電話號碼或驗證提供者資訊。這個新帳戶以 Firebase 專案的形式儲存,無論使用者以何種方式登入,都能從專案中的每個應用程式識別使用者。
-
在應用程式中,您可以從
FirebaseUser
物件取得使用者的基本個人資料。請參閱「 管理使用者」一文。 在 Firebase 即時資料庫和 Cloud Storage 安全性規則中,您可以從
auth
變數取得已登入使用者的專屬 ID,並使用該 ID 控管使用者可存取的資料。
您可以將驗證提供者憑證連結至現有的使用者帳戶,讓使用者透過多個驗證提供者登入您的應用程式。
如要登出使用者,請呼叫
signOut
:
Kotlin+KTX
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();