在 Android 中使用電子郵件連結透過 Firebase 進行身份驗證

您可以使用 Firebase 身份驗證來登錄用戶,方法是向用戶發送一封包含鏈接的電子郵件,用戶可以點擊該鏈接進行登錄。在此過程中,還會驗證用戶的電子郵件地址。

通過電子郵件登錄有很多好處:

  • 低摩擦註冊和登錄。
  • 降低跨應用程序重複使用密碼的風險,即使精心選擇的密碼也可能會破壞其安全性。
  • 能夠對用戶進行身份驗證,同時驗證用戶是否是電子郵件地址的合法所有者。
  • 用戶只需要一個可訪問的電子郵件帳戶即可登錄。不需要電話號碼或社交媒體帳戶的所有權。
  • 用戶可以安全登錄,無需提供(或記住)密碼,這在移動設備上可能很麻煩。
  • 之前使用電子郵件標識符(密碼或聯合)登錄的現有用戶可以升級為僅使用電子郵件登錄。例如,忘記密碼的用戶仍然可以登錄,而無需重置密碼。

在你開始之前

設置您的 Android 項目

  1. 如果您尚未將 Firebase 添加到您的 Android 項目中,請將其添加到您的 Android 項目中。

  2. 模塊(應用程序級)Gradle 文件(通常<project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle )中,添加 Firebase 身份驗證的依賴項安卓庫。我們建議使用Firebase Android BoM來控制庫版本控制。

    此外,作為設置 Firebase 身份驗證的一部分,您需要將 Google Play 服務 SDK 添加到您的應用中。

    Kotlin+KTX

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.3.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-ktx")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0")
    }

    通過使用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.1.2")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0")
    }

    Java

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.3.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")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0")
    }

    通過使用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.1.2")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0")
    }

要通過電子郵件鏈接登錄用戶,您必須首先為您的 Firebase 項目啟用電子郵件提供商和電子郵件鏈接登錄方法:

  1. Firebase 控制台中,打開“身份驗證”部分。
  2. 登錄方法選項卡上,啟用電子郵件/密碼提供商。請注意,必須啟用電子郵件/密碼登錄才能使用電子郵件鏈接登錄。
  3. 在同一部分中,啟用電子郵件鏈接(無密碼登錄)登錄方法。
  4. 單擊“保存”

要啟動身份驗證流程,請向用戶顯示一個界​​面,提示用戶提供電子郵件地址,然後調用sendSignInLinkToEmail請求 Firebase 將身份驗證鏈接發送到用戶的電子郵件。

  1. 構造ActionCodeSettings對象,該對象為 Firebase 提供有關如何構造電子郵件鏈接的說明。設置以下字段:

    • url :要嵌入的深層鏈接以及要傳遞的任何其他狀態。該鏈接的域必須在 Firebase 控制台授權域列表中列入白名單,可以通過轉到登錄方法選項卡(身份驗證 -> 登錄方法)找到該列表。如果用戶的設備上未安裝該應用程序並且無法安裝該應用程序,則該鏈接會將用戶重定向到此 URL。
    • androidPackageNameIOSBundleId :在 Android 或 Apple 設備上打開登錄鏈接時要使用的應用程序。詳細了解如何配置 Firebase 動態鏈接以通過移動應用打開電子郵件操作鏈接。
    • handleCodeInApp :設置為 true。與其他帶外電子郵件操作(密碼重置和電子郵件驗證)不同,登錄操作必須始終在應用程序中完成。這是因為,在流程結束時,用戶應該登錄並且他們的身份驗證狀態會保留在應用程序中。
    • dynamicLinkDomain :當為項目定義多個自定義動態鏈接域時,指定當通過指定的移動應用程序打開鏈接時要使用哪一個(例如example.page.link )。否則將自動選擇第一個域。

    Kotlin+KTX

    val actionCodeSettings = actionCodeSettings {
        // URL you want to redirect back to. The domain (www.example.com) for this
        // URL must be whitelisted in the Firebase Console.
        url = "https://www.example.com/finishSignUp?cartId=1234"
        // This must be true
        handleCodeInApp = true
        setIOSBundleId("com.example.ios")
        setAndroidPackageName(
            "com.example.android",
            true, // installIfNotAvailable
            "12", // minimumVersion
        )
    }

    Java

    ActionCodeSettings actionCodeSettings =
            ActionCodeSettings.newBuilder()
                    // URL you want to redirect back to. The domain (www.example.com) for this
                    // URL must be whitelisted in the Firebase Console.
                    .setUrl("https://www.example.com/finishSignUp?cartId=1234")
                    // This must be true
                    .setHandleCodeInApp(true)
                    .setIOSBundleId("com.example.ios")
                    .setAndroidPackageName(
                            "com.example.android",
                            true, /* installIfNotAvailable */
                            "12"    /* minimumVersion */)
                    .build();

    要了解有關 ActionCodeSettings 的更多信息,請參閱電子郵件操作中的傳遞狀態部分。

  2. 詢問用戶的電子郵件。

  3. 將身份驗證鏈接發送到用戶的電子郵件,並保存用戶的電子郵件,以防用戶在同一設備上完成電子郵件登錄。

    Kotlin+KTX

    Firebase.auth.sendSignInLinkToEmail(email, actionCodeSettings)
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Log.d(TAG, "Email sent.")
            }
        }

    Java

    FirebaseAuth auth = FirebaseAuth.getInstance();
    auth.sendSignInLinkToEmail(email, actionCodeSettings)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "Email sent.");
                    }
                }
            });

安全問題

為了防止登錄鏈接被用於以非預期用戶身份或在非預期設備上登錄,Firebase Auth 要求在完成登錄流程時提供用戶的電子郵件地址。為了成功登錄,此電子郵件地址必須與登錄鏈接最初發送到的地址匹配。

您可以在發送登錄電子郵件時,通過在本地存儲他們的電子郵件地址(例如使用 SharedPreferences),為在請求鏈接的同一設備上打開登錄鏈接的用戶簡化此流程。然後,使用這個地址來完成流程。不要在重定向 URL 參數中傳遞用戶的電子郵件並重複使用它,因為這可能會啟用會話注入。

登錄完成後,任何先前未經驗證的登錄機制都將從用戶中刪除,並且任何現有會話都將失效。例如,如果某人之前使用相同的電子郵件和密碼創建了未經驗證的帳戶,則該用戶的密碼將被刪除,以防止聲稱擁有所有權並創建該未經驗證的帳戶的冒充者使用未經驗證的電子郵件和密碼再次登錄。

另請確保在生產中使用 HTTPS URL,以避免您的鏈接可能被中間服務器攔截。

在 Android 應用程序中完成登錄

Firebase 身份驗證使用 Firebase 動態鏈接將電子郵件鏈接發送到移動設備。要通過移動應用程序完成登錄,必須將應用程序配置為檢測傳入的應用程序鏈接,解析底層深層鏈接,然後完成登錄。

Firebase Auth 在發送要在移動應用程序中打開的鏈接時使用Firebase 動態鏈接。為了使用此功能,必須在 Firebase 控制台中配置動態鏈接。

  1. 啟用 Firebase 動態鏈接:

    1. Firebase 控制台中,打開動態鏈接部分。
    2. 如果您尚未接受動態鏈接條款並創建動態鏈接域,請立即執行。

      如果您已經創建了動態鏈接域,請記下它。動態鏈接域通常類似於以下示例:

      example.page.link

      當您配置 Apple 或 Android 應用程序以攔截傳入鏈接時,您將需要此值。

  2. 配置 Android 應用程序:

    1. 為了處理來自 Android 應用程序的這些鏈接,需要在 Firebase 控制台項目設置中指定 Android 包名稱。另外,還需要提供申請證書的SHA-1和SHA-256。
    2. 現在您已經添加了動態鏈接域並確保您的 Android 應用程序配置正確,動態鏈接將從啟動器 Activity 開始重定向到您的應用程序。
    3. 如果您希望動態鏈接重定向到特定活動,則需要在AndroidManifest.xml文件中配置 Intent 過濾器。這可以通過在意圖過濾器中指定動態鏈接域或電子郵件操作處理程序來完成。默認情況下,電子郵件操作處理程序託管在如下例所示的域上:
      PROJECT_ID.firebaseapp.com/
    4. 注意事項:
      1. 不要指定您在 Intent 過濾器中的 actionCodeSettings 上設置的 URL。
      2. 創建動態鏈接域時,您可能還創建了一個短 URL 鏈接。這個短網址不會被傳遞;不要配置您的 Intent 過濾器以使用android:pathPrefix屬性捕獲它。這意味著您將無法捕獲應用程序不同部分中的不同動態鏈接。但是,您可以檢查鏈接中的mode查詢參數以查看正在嘗試執行什麼操作,或者使用 SDK 方法(例如isSignInWithEmailLink來查看您的應用收到的鏈接是否執行您想要的操作。
    5. 有關接收動態鏈接的更多信息,請參閱接收 Android 動態鏈接說明

收到上述鏈接後,請驗證該鏈接是否用於電子郵件鏈接身份驗證並完成登錄。

Kotlin+KTX

val auth = Firebase.auth
val intent = intent
val emailLink = intent.data.toString()

// Confirm the link is a sign-in with email link.
if (auth.isSignInWithEmailLink(emailLink)) {
    // Retrieve this from wherever you stored it
    val email = "someemail@domain.com"

    // The client SDK will parse the code from the link for you.
    auth.signInWithEmailLink(email, emailLink)
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Log.d(TAG, "Successfully signed in with email link!")
                val result = task.result
                // You can access the new user via result.getUser()
                // Additional user info profile *not* available via:
                // result.getAdditionalUserInfo().getProfile() == null
                // You can check if the user is new or existing:
                // result.getAdditionalUserInfo().isNewUser()
            } else {
                Log.e(TAG, "Error signing in with email link", task.exception)
            }
        }
}

Java

FirebaseAuth auth = FirebaseAuth.getInstance();
Intent intent = getIntent();
String emailLink = intent.getData().toString();

// Confirm the link is a sign-in with email link.
if (auth.isSignInWithEmailLink(emailLink)) {
    // Retrieve this from wherever you stored it
    String email = "someemail@domain.com";

    // The client SDK will parse the code from the link for you.
    auth.signInWithEmailLink(email, emailLink)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "Successfully signed in with email link!");
                        AuthResult result = task.getResult();
                        // You can access the new user via result.getUser()
                        // Additional user info profile *not* available via:
                        // result.getAdditionalUserInfo().getProfile() == null
                        // You can check if the user is new or existing:
                        // result.getAdditionalUserInfo().isNewUser()
                    } else {
                        Log.e(TAG, "Error signing in with email link", task.getException());
                    }
                }
            });
}

要了解有關如何在 Apple 應用程序中使用電子郵件鏈接處理登錄的更多信息,請參閱Apple 平台指南

要了解如何在 Web 應用程序中使用電子郵件鏈接處理登錄,請參閱Web 指南

您還可以將此身份驗證方法鏈接到現有用戶。例如,之前通過其他提供商(例如電話號碼)進行身份驗證的用戶可以將此登錄方法添加到其現有帳戶中。

不同之處在於操作的後半部分:

Kotlin+KTX

// Construct the email link credential from the current URL.
val credential = EmailAuthProvider.getCredentialWithLink(email, emailLink)

// Link the credential to the current user.
Firebase.auth.currentUser!!.linkWithCredential(credential)
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Log.d(TAG, "Successfully linked emailLink credential!")
            val result = task.result
            // You can access the new user via result.getUser()
            // Additional user info profile *not* available via:
            // result.getAdditionalUserInfo().getProfile() == null
            // You can check if the user is new or existing:
            // result.getAdditionalUserInfo().isNewUser()
        } else {
            Log.e(TAG, "Error linking emailLink credential", task.exception)
        }
    }

Java

// Construct the email link credential from the current URL.
AuthCredential credential =
        EmailAuthProvider.getCredentialWithLink(email, emailLink);

// Link the credential to the current user.
auth.getCurrentUser().linkWithCredential(credential)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "Successfully linked emailLink credential!");
                    AuthResult result = task.getResult();
                    // You can access the new user via result.getUser()
                    // Additional user info profile *not* available via:
                    // result.getAdditionalUserInfo().getProfile() == null
                    // You can check if the user is new or existing:
                    // result.getAdditionalUserInfo().isNewUser()
                } else {
                    Log.e(TAG, "Error linking emailLink credential", task.getException());
                }
            }
        });

這也可用於在運行敏感操作之前重新驗證電子郵件鏈接用戶。

Kotlin+KTX

// Construct the email link credential from the current URL.
val credential = EmailAuthProvider.getCredentialWithLink(email, emailLink)

// Re-authenticate the user with this credential.
Firebase.auth.currentUser!!.reauthenticateAndRetrieveData(credential)
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            // User is now successfully reauthenticated
        } else {
            Log.e(TAG, "Error reauthenticating", task.exception)
        }
    }

Java

// Construct the email link credential from the current URL.
AuthCredential credential =
        EmailAuthProvider.getCredentialWithLink(email, emailLink);

// Re-authenticate the user with this credential.
auth.getCurrentUser().reauthenticateAndRetrieveData(credential)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // User is now successfully reauthenticated
                } else {
                    Log.e(TAG, "Error reauthenticating", task.getException());
                }
            }
        });

但是,由於該流程可能最終到達原始用戶未登錄的其他設備,因此該流程可能無法完成。在這種情況下,可以向用戶顯示錯誤,迫使他們在同一設備上打開鏈接。可以在鏈接中傳遞一些狀態以提供有關操作類型和用戶 uid 的信息。

如果您支持通過電子郵件進行基於密碼和基於鏈接的登錄,要區分密碼/鏈接用戶的登錄方法,請使用fetchSignInMethodsForEmail 。這對於標識符優先的流程非常有用,在該流程中,首先要求用戶提供電子郵件,然後向用戶提供登錄方法:

Kotlin+KTX

Firebase.auth.fetchSignInMethodsForEmail(email)
    .addOnSuccessListener { result ->
        val signInMethods = result.signInMethods!!
        if (signInMethods.contains(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD)) {
            // User can sign in with email/password
        } else if (signInMethods.contains(EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD)) {
            // User can sign in with email/link
        }
    }
    .addOnFailureListener { exception ->
        Log.e(TAG, "Error getting sign in methods for user", exception)
    }

Java

auth.fetchSignInMethodsForEmail(email)
        .addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
            @Override
            public void onComplete(@NonNull Task<SignInMethodQueryResult> task) {
                if (task.isSuccessful()) {
                    SignInMethodQueryResult result = task.getResult();
                    List<String> signInMethods = result.getSignInMethods();
                    if (signInMethods.contains(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD)) {
                        // User can sign in with email/password
                    } else if (signInMethods.contains(EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD)) {
                        // User can sign in with email/link
                    }
                } else {
                    Log.e(TAG, "Error getting sign in methods for user", task.getException());
                }
            }
        });

如上所述,電子郵件/密碼和電子郵件/鏈接被視為具有不同登錄方法的相同EmailAuthProvider (相同PROVIDER_ID )。

下一步

用戶首次登錄後,系統會創建一個新的用戶帳戶,並將其鏈接到用戶登錄時使用的憑據(即用戶名和密碼、電話號碼或身份驗證提供商信息)。此新帳戶將作為 Firebase 項目的一部分存儲,並且可用於識別項目中每個應用中的用戶,無論用戶如何登錄。

  • 在您的應用中,您可以從FirebaseUser對象獲取用戶的基本個人資料信息。請參閱管理用戶

  • 在 Firebase 實時數據庫和雲存儲安全規則中,您可以從auth變量獲取登錄用戶的唯一用戶 ID,並使用它來控制用戶可以訪問哪些數據。

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

要註銷用戶,請調用signOut

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();