開始在 Android 上使用 Firebase 驗證

將應用程式連結至 Firebase

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

在應用程式中加入 Firebase 驗證

  1. 模組 (應用程式層級) 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 開發人員都能 依附於主要程式庫模組 (詳情請參閱 這項計畫的常見問題)。

  2. 如要使用驗證供應商,您需要前往 Firebase 控制台:前往 Firebase 驗證中的「Sign-in Method」(登入方式) 頁面 專區中啟用電子郵件/密碼登入功能和其他識別資訊提供者 挑選的應用程式

(選用) 使用 Firebase 本機模擬器套件設計原型並進行測試

在說明應用程式如何驗證使用者之前,我們先介紹一組 可用來設計驗證原型及測試驗證功能的工具: Firebase 本機模擬器套件。如果你正在考慮採用驗證方法 並嘗試運用公開和私人資料,嘗試不同的資料模型 運用驗證和 Firebase 安全性規則,或是設計登入使用者介面的原型, 無需部署有效服務就在本機上運作,會是個好主意。

驗證模擬器屬於本機模擬器套件的一部分, 可讓應用程式與模擬的資料庫內容和設定互動,例如: 以及選用的模擬專案資源 (函式、其他資料庫 和安全性規則)。

使用驗證模擬器只需完成幾個步驟:

  1. 將一行程式碼新增至應用程式的測試設定,即可與模擬器連線。
  2. 從本機專案目錄的根目錄中執行 firebase emulators:start
  3. 使用本機模擬器套件 UI 進行互動式原型設計,或 驗證模擬器 REST API,用於非互動式測試。

如需詳細指南,請參閱「將應用程式連線至驗證模擬器」一文。 詳情請參閱「本機模擬器套件簡介」。

接下來說明如何驗證使用者。

查看目前的驗證狀態

  1. 宣告 FirebaseAuth 的例項。

    Kotlin+KTX

    private lateinit var auth: FirebaseAuth

    Java

    private FirebaseAuth mAuth;
  2. onCreate() 方法中,初始化 FirebaseAuth 例項。

    Kotlin+KTX

    // Initialize Firebase Auth
    auth = Firebase.auth

    Java

    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  3. 初始化「活動」時,請檢查使用者目前是否已登入 。

    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();
        }
    }

註冊新使用者

建立能接收電子郵件地址和密碼的新 createAccount 方法, 會以這種方式建立新使用者 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);
                }
            }
        });

新增表單,提供新使用者的電子郵件地址和密碼註冊,並呼叫這個新工作階段 方法。您可以在「 快速入門導覽課程範例

登入現有使用者

建立新的 signIn 方法,採用一組電子郵件地址和密碼。 才能驗證系統,然後再透過 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);
                }
            }
        });

請新增表單,讓使用者透過自己的電子郵件地址和密碼登入,並呼叫這個新表單 方法。您可以在「 快速入門導覽課程範例

存取使用者資訊

如果使用者成功登入,您可以從下列位置取得他們的帳戶資料 透過 getCurrentUser 方法傳送任何路徑點。

Kotlin+KTX

val user = Firebase.auth.currentUser
user?.let {
    // Name, email address, and profile photo Url
    val name = it.displayName
    val email = it.email
    val photoUrl = it.photoUrl

    // Check if user's email is verified
    val emailVerified = it.isEmailVerified

    // The user's ID, unique to the Firebase project. Do NOT use this value to
    // authenticate with your backend server, if you have one. Use
    // FirebaseUser.getIdToken() instead.
    val uid = it.uid
}

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // Name, email address, and profile photo Url
    String name = user.getDisplayName();
    String email = user.getEmail();
    Uri photoUrl = user.getPhotoUrl();

    // Check if user's email is verified
    boolean emailVerified = user.isEmailVerified();

    // The user's ID, unique to the Firebase project. Do NOT use this value to
    // authenticate with your backend server, if you have one. Use
    // FirebaseUser.getIdToken() instead.
    String uid = user.getUid();
}

後續步驟

探索新增其他身分識別和驗證服務的指南: