Catch up on highlights from Firebase at Google I/O 2023. Learn more

使用自定義身份驗證系統在 Android 上使用 Firebase 進行身份驗證

您可以將 Firebase 身份驗證與自定義身份驗證系統集成,方法是修改您的身份驗證服務器以在用戶成功登錄時生成自定義簽名令牌。您的應用程序接收此令牌並使用它通過 Firebase 進行身份驗證。

在你開始之前

  1. 如果您還沒有,請將 Firebase 添加到您的 Android 項目中
  2. 在您的模塊(應用級)Gradle 文件(通常為<project>/<app-module>/build.gradle )中,添加 Firebase 身份驗證 Android 庫的依賴項。我們建議使用Firebase Android BoM來控制庫版本。

    Kotlin+KTX

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.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-ktx'
    }
    

    通過使用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-ktx:22.0.0'
    }
    

    Java

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.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:22.0.0'
    }
    
  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. 初始化 Activity 時,檢查用戶當前是否已登錄:

    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 Realtime Database 和 Cloud Storage Security Rules中,您可以從auth變量中獲取登錄用戶的唯一用戶 ID,並使用它來控制用戶可以訪問的數據。

您可以允許用戶使用多個身份驗證提供程序登錄您的應用程序,方法是將身份驗證提供程序憑據鏈接到現有用戶帳戶。

要註銷用戶,請調用signOut

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();