在 Android 上使用密碼型帳戶進行 Firebase 驗證

您可以使用 Firebase Authentication,讓使用者透過電子郵件地址和密碼向 Firebase 驗證身分,並管理應用程式的密碼型帳戶。

如需 AI 輔助,請將下列提示詞複製到 AI 程式碼代理 (例如 Android Studio 內建 Gemini、Antigravity、Claude Code、Codex 和 Cursor)。你可以自訂提示,並與代理程式互動。如需詳細安裝資訊,請參閱 Firebase Agent Skills

Help me use Firebase in my app.
1. Make sure that **Firebase agent skills** are installed and updated. For Claude Code, Codex, or Cursor agents, help me install the Firebase plugin. For other agents, run `npx skills add firebase/agent-skills`. Always try to use **Firebase agent skills** for Firebase-related tasks.
2. Help me set up and use Firebase Authentication with email and password authentication in my app.

事前準備

  1. 如果您尚未將 Firebase 新增至 Android 專案,請先新增。

  2. 如果尚未將應用程式連結至 Firebase 專案,請從 Firebase 控制台進行連結。
  3. 為 Firebase 專案啟用電子郵件/密碼做為登入供應商:
    1. Firebase 控制台中,依序點選「安全性」>「驗證」
    2. 在「登入方式」分頁中,啟用「電子郵件地址/密碼」登入供應商。
    3. 按一下「儲存」
  4. 模組 (應用程式層級) 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.19.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.2.0")
    }

建立以密碼為基礎的帳戶

如要建立含有密碼的新使用者帳戶,請在應用程式的登入活動中完成下列步驟:

  1. 在註冊活動的 onCreate 方法中,取得 FirebaseAuth 物件的共用執行個體:

    Kotlin

    private lateinit var auth: FirebaseAuth
    // ...
    // Initialize Firebase Auth
    auth = Firebase.auth

    Java

    private FirebaseAuth mAuth;
    // ...
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  2. 初始化 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();
        }
    }
  3. 當新使用者透過應用程式的註冊表單註冊時,請完成應用程式要求的任何新帳戶驗證步驟,例如確認新帳戶的密碼輸入正確,且符合複雜度規定。
  4. 將新使用者的電子郵件地址和密碼傳遞至 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 方法取得使用者的帳戶資料。

透過電子郵件地址和密碼登入使用者帳戶

使用密碼登入使用者的步驟,與建立新帳戶的步驟類似。在應用程式的登入活動中,請執行下列操作:

  1. 在登入活動的 onCreate 方法中,取得 FirebaseAuth 物件的共用執行個體:

    Kotlin

    private lateinit var auth: FirebaseAuth
    // ...
    // Initialize Firebase Auth
    auth = Firebase.auth

    Java

    private FirebaseAuth mAuth;
    // ...
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  2. 初始化 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();
        }
    }
  3. 使用者登入應用程式時,請將使用者的電子郵件地址和密碼傳遞至 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 控制台的「安全性」>「驗證」>「設定」分頁,然後前往「密碼政策」部分:

驗證設定

Firebase Authentication 密碼政策支援下列密碼規定:

  • 須有小寫字元

  • 須有大寫字元

  • 必須包含數字字元

  • 必須包含非英數字元

    下列字元符合非英數字元規定: ^ $ * . [ ] { } ( ) ? " ! @ # % & / \ , > < ' : ; | _ ~

  • 密碼長度下限 (6 到 30 個字元,預設為 6 個字元)

  • 密碼長度上限 (最多 4096 個半形字元)

您可以透過下列兩種模式強制執行密碼政策:

  • 要求:使用者如未改用符合政策的密碼,就無法註冊。

  • 通知:使用者能以不合規定的密碼註冊,使用這個模式時,您應在用戶端檢查使用者的密碼是否符合政策規定,如果不符合,請以某種方式提示使用者更新密碼。

新使用者一律須選擇符合政策的密碼。

如果您有活躍使用者,建議不要啟用「登入時強制升級」,除非您打算封鎖密碼不符合政策的使用者存取權。請改用通知模式,讓使用者以目前的密碼登入,並告知他們密碼不符合哪些規定。

建議:啟用電子郵件列舉防護

如果電子郵件地址必須註冊但未註冊 (例如使用電子郵件地址和密碼登入時),或必須未使用但已註冊 (例如變更使用者的電子郵件地址時),部分以電子郵件地址做為參數的 Firebase Authentication 方法會擲回特定錯誤。雖然這項功能有助於向使用者建議特定解決方法,但惡意人士也可能濫用這項功能,找出使用者註冊的電子郵件地址。

為降低這項風險,建議您確保專案已啟用電子郵件列舉防護。如要檢查這項設定,請前往 Firebase 控制台,依序點選「安全性」 >「驗證」 >「設定」分頁標籤,然後按一下「使用者動作」

請注意,啟用這項功能會變更 Firebase Authentication 的錯誤回報行為,因此請確認應用程式不會依賴更具體的錯誤。

後續步驟

使用者首次登入後,系統會建立新的使用者帳戶,並連結至使用者登入時使用的憑證 (即使用者名稱和密碼、電話號碼或驗證供應商資訊)。這個新帳戶會儲存在 Firebase 專案中,可用於識別專案中每個應用程式的使用者,無論使用者登入方式為何。

  • 在應用程式中,您可以從 FirebaseUser 物件取得使用者的基本個人資料資訊。請參閱「 管理使用者」。

  • Firebase Realtime DatabaseCloud Storage 安全規則中,您可以從 auth 變數取得登入使用者的專屬使用者 ID, 並使用該 ID 控制使用者可存取的資料。

您可以將驗證供應商憑證連結至現有使用者帳戶,允許使用者透過多個驗證供應商登入應用程式。

如要登出使用者,請呼叫 signOut

Kotlin

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();