使用自訂驗證系統在 Android 上透過 Firebase 進行驗證

您可以修改驗證伺服器,在使用者成功登入時產生自訂簽署權杖,藉此將 Firebase 驗證與自訂驗證系統整合。應用程式收到此權杖後,會使用該權杖進行 Firebase 驗證。

事前準備

  1. 如果您尚未將 Firebase 新增至 Android 專案,請先完成這項操作。
  2. 模組 (應用程式層級) Gradle 檔案 (通常是 <project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle) 中,新增 Android 專用 Firebase 驗證程式庫的依附元件。
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.1.1"))
    
        // 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 開發人員都能使用主要的程式庫模組 (詳情請參閱這項計畫的常見問題)。
  3. 取得專案的伺服器金鑰:
    1. 前往專案設定中的服務帳戶頁面。
    2. 在「服務帳戶」頁面的「Firebase Admin SDK」部分底部,按一下「產生新的私密金鑰」
    3. 新服務帳戶的公開/私密金鑰組會自動儲存至您的電腦。將這個檔案複製到您的驗證伺服器。

透過 Firebase 驗證

  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
        updateUI(currentUser)
    }

    Java

    @Override
    public void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        updateUI(currentUser);
    }
  3. 使用者登入應用程式時,請將登入憑證 (例如使用者名稱和密碼) 傳送至您的驗證伺服器。您的伺服器會檢查憑證,並傳回有效的自訂權杖
  4. 從驗證伺服器收到自訂權杖後,請將該權杖傳遞至 signInWithCustomToken 以便登入使用者:

    Kotlin+KTX

    customToken?.let {
        auth.signInWithCustomToken(it)
            .addOnCompleteListener(this) { task ->
                if (task.isSuccessful) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "signInWithCustomToken:success")
                    val user = auth.currentUser
                    updateUI(user)
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "signInWithCustomToken:failure", task.exception)
                    Toast.makeText(
                        baseContext,
                        "Authentication failed.",
                        Toast.LENGTH_SHORT,
                    ).show()
                    updateUI(null)
                }
            }
    }

    Java

    mAuth.signInWithCustomToken(mCustomToken)
            .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, "signInWithCustomToken:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCustomToken:failure", task.getException());
                        Toast.makeText(CustomAuthActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        updateUI(null);
                    }
                }
            });
    如果登入成功,AuthStateListener 即可使用 getCurrentUser 方法取得使用者的帳戶資料。

後續步驟

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

  • 在應用程式中,您可以透過 FirebaseUser 物件取得使用者的基本個人資料。請參閱 管理使用者一文。

  • 在 Firebase 即時資料庫和 Cloud Storage 安全性規則中,您可以透過 auth 變數取得登入使用者的專屬 ID,並使用該 ID 控管使用者可存取哪些資料。

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

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

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();