您可以使用 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.0.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 程式庫版本。
(替代做法) 新增 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();