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

您可以使用 Firebase 驗證功能,讓使用者透過 Firebase 使用自己的電子郵件地址和密碼,管理應用程式的 使用 API

事前準備

  1. 如果還沒試過 將 Firebase 新增至您的 Android 專案

  2. 如果您尚未將應用程式連結至 Firebase 專案,請前往 Firebase 控制台
  3. 啟用電子郵件/密碼登入功能:
    1. Firebase 控制台開啟 找到「Auth」(驗證) 區段。
    2. 在「Sign in method」分頁中啟用「Email/password」登入 方法並點選「儲存」
  4. 模組 (應用程式層級) 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.2"))
    
        // 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")
    }
    
    在尋找 Kotlin 專用的程式庫模組嗎?距離開始還有 2023 年 10 月 (Firebase BoM 32.5.0),Kotlin 和 Java 開發人員都能 依附於主要程式庫模組 (詳情請參閱 這項計畫的常見問題)。

建立以密碼為基礎的帳戶

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

  1. 在註冊活動的 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();
  2. 初始化「活動」時,請檢查使用者目前是否登入:

    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();
        }
    }
  3. 當新使用者透過應用程式的註冊表單註冊時,請完成新的使用者 帳戶驗證步驟,例如驗證 已正確輸入新帳戶的密碼,符合您的複雜程度 Google Cloud 就是最佳選擇
  4. 傳送新使用者的電子郵件地址和密碼,建立新帳戶 至 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 方法 取得使用者的帳戶資料。

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

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

  1. 在登入活動的 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();
  2. 初始化「活動」時,請檢查使用者目前是否登入:

    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();
        }
    }
  3. 使用者登入應用程式時,傳送使用者的電子郵件地址並 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。 控管使用者可以存取的資料

您可以讓使用者透過多重驗證機制登入您的應用程式 將驗證供應商憑證連結至 現有的使用者帳戶

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

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();