您可以使用 Firebase Authentication,讓使用者透過電子郵件地址和密碼向 Firebase 驗證身分,並管理應用程式的密碼型帳戶。
事前準備
如果您尚未將 Firebase 新增至 Android 專案,請先新增。
- 如果尚未將應用程式連結至 Firebase 專案,請從 Firebase 控制台進行連結。
- 啟用電子郵件地址/密碼登入功能:
- 在 Firebase 控制台中,開啟「Auth」(驗證) 部分。
- 在「登入方式」分頁中,啟用「電子郵件地址/密碼」登入方式,然後按一下「儲存」。
在模組 (應用程式層級) Gradle 檔案 (通常是
<project>/<app-module>/build.gradle.kts
或<project>/<app-module>/build.gradle
) 中,加入 Android 適用的 Firebase Authentication 程式庫依附元件。建議使用 Firebase Android BoM 控制程式庫版本。dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.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 程式庫版本。
(替代做法) 不使用 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:24.0.0") }
建立密碼帳戶
如要使用密碼建立新的使用者帳戶,請在應用程式的登入活動中完成下列步驟:
- 在註冊活動的
onCreate
方法中,取得FirebaseAuth
物件的共用例項:Kotlin
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
- 初始化 Activity 時,請檢查使用者目前是否已登入:
Kotlin
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
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
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
- 初始化 Activity 時,請檢查使用者目前是否已登入:
Kotlin
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
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 控制台的「Authentication Settings」頁面中,開啟「Password policy」分頁:
Firebase Authentication 密碼政策支援下列密碼規定:
須有小寫字元
須有大寫字元
必須包含數字字元
須有非英數字元
下列字元符合非英數字元規定:
^ $ * . [ ] { } ( ) ? " ! @ # % & / \ , > < ' : ; | _ ~
密碼長度下限 (6 到 30 個字元,預設為 6 個字元)
密碼長度上限 (最多 4096 個半形字元)
您可以透過下列兩種模式強制執行密碼政策:
要求:使用者如未改用符合政策的密碼,就無法註冊。
通知:使用者可以註冊不符合規定的密碼。使用這個模式時,您應在用戶端檢查使用者的密碼是否符合政策規定,如果不符合,請以某種方式提示使用者更新密碼。
新使用者一律須選擇符合政策的密碼。
如果您有活躍使用者,建議不要啟用「登入時強制升級」,除非您打算禁止密碼不符合政策的使用者存取帳戶。請改用通知模式,讓使用者以目前的密碼登入,並告知他們密碼不符合哪些規定。
建議:啟用電子郵件列舉防護功能
如果電子郵件地址必須註冊但未註冊 (例如使用電子郵件地址和密碼登入時),或必須未使用但已註冊 (例如變更使用者的電子郵件地址時),部分以電子郵件地址做為參數的 Firebase Authentication 方法會擲回特定錯誤。雖然這有助於向使用者建議特定解決方法,但惡意行為人也可能濫用這項功能,找出使用者註冊的電子郵件地址。
為降低這類風險,建議您使用 Google Cloud gcloud
工具,為專案啟用電子郵件列舉保護機制。請注意,啟用這項功能會變更 Firebase Authentication 的錯誤回報行為,請確保應用程式不會依賴更具體的錯誤。
後續步驟
使用者首次登入後,系統會建立新的使用者帳戶,並連結至使用者登入時使用的憑證 (即使用者名稱和密碼、電話號碼或驗證供應商資訊)。這個新帳戶會儲存在 Firebase 專案中,可用於識別專案中每個應用程式的使用者,無論使用者登入方式為何。
-
在應用程式中,您可以從
FirebaseUser
物件取得使用者的基本個人資料資訊。請參閱「 管理使用者」。 在 Firebase Realtime Database 和 Cloud Storage 安全規則中,您可以從
auth
變數取得已登入使用者的專屬使用者 ID, 並使用該 ID 控制使用者可存取的資料。
您可以將驗證供應商憑證連結至現有使用者帳戶,允許使用者透過多個驗證供應商登入應用程式。
如要登出使用者,請呼叫
signOut
:
Kotlin
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();