您可以使用 Firebase 驗證功能,向使用者傳送含有連結的電子郵件,讓他們點選即可登入。在過程中,系統也會驗證使用者的電子郵件地址。
使用電子郵件登入有以下優點:
- 簡化註冊和登入程序。
- 降低應用程式之間重複使用密碼的風險,可能導致選取的密碼安全性不佳。
- 驗證使用者身分,同時驗證使用者是否為電子郵件地址的合法擁有者。
- 使用者只需具備可存取的電子郵件帳戶即可登入。不需要具備電話號碼或社群媒體帳戶的擁有權。
- 使用者不需提供 (或記住) 密碼,即可安全登入,這對行動裝置來說可能很麻煩。
- 先前以電子郵件 ID (密碼或聯合) 登入的現有使用者之升級,可以升級到僅使用電子郵件登入。舉例來說,如果使用者忘記密碼,仍然可以在不需要重設密碼的情況下登入。
事前準備
設定 Android 專案
如果您尚未將 Firebase 新增至 Android 專案,請先完成這項作業。
在模組 (應用程式層級) Gradle 檔案 (通常是
<project>/<app-module>/build.gradle.kts
或<project>/<app-module>/build.gradle
) 中,新增 Android 專用 Firebase 驗證程式庫的依附元件。建議您使用 Firebase Android BoM 控管程式庫的版本管理。此外,設定 Firebase 驗證時,您必須將 Google Play 服務 SDK 新增至您的應用程式。
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")
// Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:21.2.0") }只要使用 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")
// Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:21.2.0") }
為 Firebase 專案啟用電子郵件連結登入功能
如要透過電子郵件連結登入使用者,您必須先為 Firebase 專案啟用電子郵件服務供應商和電子郵件連結登入方式:
- 在 Firebase 控制台開啟「驗證」專區。
- 在「Sign in method」分頁中啟用「Email/Password」供應商。請注意,您必須啟用電子郵件/密碼登入功能,才能使用電子郵件連結登入。
- 在相同區段中,啟用「Email link (無密碼登入)」登入方式。
- 按一下「儲存」。
傳送驗證連結至使用者的電子郵件地址
如要啟動驗證流程,請向使用者顯示一個可提示使用者提供電子郵件地址的介面,然後呼叫 sendSignInLinkToEmail
以要求 Firebase 將驗證連結傳送至使用者的電子郵件。
建構 ActionCodeSettings 物件,提供 Firebase 如何建構電子郵件連結的操作說明。設定下列欄位:
url
:要嵌入的深層連結,以及要一併傳遞的任何其他狀態。連結的網域必須在 Firebase 控制台的授權網域清單中加入許可清單,只要前往「登入方式」分頁 (依序點選「驗證」->「登入方式」),就能找到該網域。如果使用者的裝置上未安裝應用程式,且無法安裝應用程式,這個連結會將使用者重新導向至這個網址。androidPackageName
和IOSBundleId
:在 Android 或 Apple 裝置上開啟登入連結時使用的應用程式。進一步瞭解如何設定 Firebase Dynamic Links,以透過行動應用程式開啟電子郵件動作連結。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,請參閱「電子郵件動作中的票證狀態」一節。
要求使用者提供電子郵件地址。
傳送驗證連結至使用者的電子郵件,並儲存使用者的電子郵件地址,以便在使用者在同一部裝置上完成電子郵件登入時使用。
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 驗證要求在完成登入流程時必須提供使用者的電子郵件地址。這個電子郵件地址必須與最初的登入連結寄送地址相符,才能成功登入。
當使用者在要求連結的裝置上開啟登入連結時,您可以簡化這項程序,例如將電子郵件地址儲存在本機 (例如在您傳送登入電子郵件時使用 SharedPreferences)。接著,請使用這個地址完成流程。請勿在重新導向網址參數中傳遞使用者的電子郵件,然後重新使用,因為這可能會啟用工作階段插入功能。
登入完成後,所有先前未經驗證的登入機制都會從使用者中移除,且所有現有工作階段都將失效。例如,如果某人之前已使用相同電子郵件地址和密碼建立未經驗證的帳戶,系統會移除使用者的密碼,以防止冒用擁有權的冒用者在建立未經驗證的帳戶時,使用未經驗證的電子郵件和密碼重新登入。
此外,請務必在實際工作環境中使用 HTTPS 網址,避免中介伺服器攔截您的連結。
在 Android 應用程式中完成登入程序
Firebase 驗證會使用 Firebase 動態連結將電子郵件連結傳送至行動裝置。如要透過行動應用程式完成登入,您必須將應用程式設為偵測傳入的應用程式連結,剖析基礎深層連結,然後完成登入程序。
設定 Firebase Dynamic Links
如果傳送的連結是專為行動應用程式開啟的連結,Firebase 驗證會使用 Firebase 動態連結。如要使用這項功能,您「必須」在 Firebase 控制台中設定 Dynamic Links。
啟用 Firebase Dynamic Links:
- 在 Firebase 控制台開啟「Dynamic Links」部分。
-
如果您尚未接受 Dynamic Links 條款,並且已建立 Dynamic Links 網域,請立即採取行動。
若您已建立 Dynamic Links 網域,請記下該網域。Dynamic Links 網域通常如以下範例所示:
example.page.link
將 Apple 或 Android 應用程式設為攔截傳入連結時,您需要用到這個值。
設定 Android 應用程式:
- 為了從 Android 應用程式處理這些連結,您需要在 Firebase 控制台的專案設定中指定 Android 套件名稱。此外,您也必須提供應用程式憑證的 SHA-1 和 SHA-256。
- 您現已新增動態連結網域,也確認 Android 應用程式設定正確無誤,動態連結會從啟動器活動開始重新導向至您的應用程式。
- 如要讓動態連結重新導向至特定活動,您必須在 AndroidManifest.xml 檔案中設定意圖篩選器。只要在意圖篩選器中指定動態連結網域或電子郵件動作處理常式即可。根據預設,電子郵件動作處理常式是由網域託管,範例如下:
PROJECT_ID.firebaseapp.com/
- 注意事項:
- 請勿在意圖篩選器的 actionCodeSettings 指定設定的網址。
- 建立動態連結網域時,您可能也建立了短網址連結。這個短網址不會傳遞;請「不要」設定意圖篩選器,以使用
android:pathPrefix
屬性擷取意圖。這表示您將無法在應用程式的不同部分擷取不同的動態連結。不過,您「可以」檢查連結中的mode
查詢參數,瞭解要執行的作業類型,或使用isSignInWithEmailLink
等 SDK 方法,查看應用程式收到的連結是否達到所需。
- 如要進一步瞭解如何接收動態連結,請參閱接收 Android Dynamic Links 操作說明。
驗證連結並登入
收到上述的連結後,請確認該連結是用於電子郵件連結驗證,並完成登入。
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 平台指南。
如要瞭解如何在網頁應用程式中處理含有電子郵件連結的登入作業,請參閱網頁指南。
連結/重新驗證電子郵件連結
您也可以將這種驗證方法連結至現有的使用者。舉例來說,使用者先前已透過其他供應商 (例如電話號碼) 完成驗證,就能將這個登入方式新增至現有的帳戶。
差異如下:作業的後半部:
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 的資訊。
已淘汰:區分電子郵件密碼與電子郵件連結
如果專案在 2023 年 9 月 15 日當天或之後建立,系統預設會啟用電子郵件列舉防護功能。這項功能可改善專案使用者帳戶的安全性,但會停用 fetchSignInMethodsForEmail()
方法 (先前建議用於實作 ID 優先流程)。
雖然您可以停用專案的電子郵件列舉防護功能,但建議您不要這麼做。
詳情請參閱電子郵件列舉防護功能說明文件。
後續步驟
使用者首次登入時,系統會建立新的使用者帳戶,並連結至憑證 (即使用者名稱與密碼、電話號碼或驗證提供者資訊),也就是使用者登入時使用的憑證。這個新帳戶會儲存在您的 Firebase 專案中,可用來識別專案中各個應用程式的使用者 (無論使用者登入方式為何)。
-
在應用程式中,您可以透過
FirebaseUser
物件取得使用者的基本個人資料。請參閱 管理使用者一文。 在 Firebase 即時資料庫和 Cloud Storage 安全性規則中,您可以透過
auth
變數取得登入使用者的專屬 ID,並使用該 ID 控管使用者可存取哪些資料。
您可以將驗證供應商憑證連結至現有的使用者帳戶,讓使用者透過多個驗證服務提供者登入您的應用程式。
如要登出使用者,請呼叫
signOut
:
Kotlin+KTX
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();