將多個驗證供應商連結至一個帳戶

您可以讓使用者透過多重驗證機制登入您的應用程式 將驗證服務供應商憑證連結至現有使用者帳戶。 無論 用於登入的驗證服務供應商例如登入後 使用密碼可以連結 Google 帳戶,並在 或者,匿名使用者也可以連結 Facebook 帳戶,之後再登入 以繼續使用應用程式。

事前準備

為兩個以上的驗證供應商新增支援 (可能包括 匿名驗證)。

如要將驗證提供者憑證與現有使用者帳戶建立連結,請按照下列步驟操作:

  1. 使用任何驗證提供者或方式登入使用者。

  2. 完成新驗證供應商的登入流程 包括呼叫其中一種 signInWith 方法舉例來說,取得 使用者的 Google ID 權杖、Facebook 存取權杖或電子郵件地址和密碼。

  3. 取得新驗證供應商的 Credential 物件:

    // Google Sign-in
    final credential = GoogleAuthProvider.credential(idToken: idToken);
    
    // Email and password sign-in
    final credential =
        EmailAuthProvider.credential(email: emailAddress, password: password);
    
    // Etc.
    
  4. Credential 物件傳遞至登入使用者的 linkWithCredential() 方法:

    try {
      final userCredential = await FirebaseAuth.instance.currentUser
          ?.linkWithCredential(credential);
    } on FirebaseAuthException catch (e) {
      switch (e.code) {
        case "provider-already-linked":
          print("The provider has already been linked to the user.");
          break;
        case "invalid-credential":
          print("The provider's credential is not valid.");
          break;
        case "credential-already-in-use":
          print("The account corresponding to the credential already exists, "
              "or is already linked to a Firebase User.");
          break;
        // See the API reference for the full list of error codes.
        default:
          print("Unknown error.");
      }
      ```
    

如果呼叫 linkWithCredential() 成功,使用者現在可以使用 任何已連結的驗證服務供應商,並存取相同的 Firebase 資料。

您可以取消驗證供應商與帳戶的連結,這樣使用者就無法 以在該平台登入帳戶

如要取消驗證提供者與使用者帳號的連結,請將提供者 ID 傳遞至 unlink() 方法。您可以取得連結至驗證供應商的供應商 ID 來自 User 物件的 providerData 屬性的使用者。

try {
  await FirebaseAuth.instance.currentUser?.unlink(providerId);
} on FirebaseAuthException catch (e) {
  switch (e.code) {
    case "no-such-provider":
      print("The user isn't linked to the provider or the provider "
          "doesn't exist.");
      break;
    default:
      print("Unknown error.");
  }
}