使用 JavaScript 將多個身份驗證提供者連結到一個帳戶

您可以透過將身分驗證提供者憑證連結到現有使用者帳戶,允許使用者使用多個驗證提供者登入您的應用程式。無論使用者用於登入的驗證提供者為何,都可以透過相同的 Firebase 使用者 ID 來識別使用者。例如,使用密碼登入的使用者可以關聯 Google 帳戶,並在將來使用任一方法登入。或者,匿名用戶可以連結 Facebook 帳戶,然後使用 Facebook 登入以繼續使用您的應用程式。

在你開始之前

在您的應用程式中新增對兩個或多個身份驗證提供者(可能包括匿名身份驗證)的支援。

若要將來自身分驗證提供者(例如 Google 或 Facebook)的憑證連結到現有使用者帳戶:

  1. 使用任何身份驗證提供者或方法登入使用者。
  2. 取得與要連結到使用者帳戶的提供者相對應的AuthProvider物件。例子:

    Web modular API

    import { GoogleAuthProvider, FacebookAuthProvider, TwitterAuthProvider, GithubAuthProvider } from "firebase/auth";
    
    const googleProvider = new GoogleAuthProvider();
    const facebookProvider = new FacebookAuthProvider();
    const twitterProvider = new TwitterAuthProvider();
    const githubProvider = new GithubAuthProvider();

    Web namespaced API

    var googleProvider = new firebase.auth.GoogleAuthProvider();
    var facebookProvider = new firebase.auth.FacebookAuthProvider();
    var twitterProvider = new firebase.auth.TwitterAuthProvider();
    var githubProvider = new firebase.auth.GithubAuthProvider();
  3. 提示使用者使用您要連結的提供者登入。您可以透過開啟彈出視窗或重定向到提供者的登入頁面來提示使用者登入。重定向方法在行動裝置上是首選。
    • 若要使用彈出視窗登錄,請呼叫linkWithPopup

      Web modular API

      import { getAuth, linkWithPopup, GoogleAuthProvider } from "firebase/auth";
      const provider = new GoogleAuthProvider();
      
      const auth = getAuth();
      linkWithPopup(auth.currentUser, provider).then((result) => {
        // Accounts successfully linked.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const user = result.user;
        // ...
      }).catch((error) => {
        // Handle Errors here.
        // ...
      });

      Web namespaced API

      auth.currentUser.linkWithPopup(provider).then((result) => {
        // Accounts successfully linked.
        var credential = result.credential;
        var user = result.user;
        // ...
      }).catch((error) => {
        // Handle Errors here.
        // ...
      });
    • 若要透過重定向到提供者的登入頁面來登錄,請呼叫linkWithRedirect :遵循使用「linkWithRedirect」時的最佳實務

      Web modular API

      import { getAuth, linkWithRedirect, GoogleAuthProvider } from "firebase/auth";
      const provider = new GoogleAuthProvider();
      
      const auth = getAuth();
      linkWithRedirect(auth.currentUser, provider)
        .then(/* ... */)
        .catch(/* ... */);

      Web namespaced API

      auth.currentUser.linkWithRedirect(provider)
        .then(/* ... */)
        .catch(/* ... */);
      用戶登入後,他們會被重新導向回您的頁面。然後,您可以在頁面載入時透過呼叫getRedirectResult來檢索登入結果:

      Web modular API

      import { getRedirectResult } from "firebase/auth";
      getRedirectResult(auth).then((result) => {
        const credential = GoogleAuthProvider.credentialFromResult(result);
        if (credential) {
          // Accounts successfully linked.
          const user = result.user;
          // ...
        }
      }).catch((error) => {
        // Handle Errors here.
        // ...
      });

      Web namespaced API

      auth.getRedirectResult().then((result) => {
        if (result.credential) {
          // Accounts successfully linked.
          var credential = result.credential;
          var user = result.user;
          // ...
        }
      }).catch((error) => {
        // Handle Errors here.
        // ...
      });
    如果使用者成功登錄,則該使用者在提供者處的帳戶將連結到該使用者在您的 Firebase 專案中的帳戶。

    如果憑證已連結到另一個使用者帳戶,帳戶連結將會失敗。在這種情況下,您必須根據您的應用程式處理帳戶和關聯資料的合併:

    Web modular API

    import { getAuth, signInWithCredential, linkWithCredential, OAuthProvider } from "firebase/auth";
    
    // The implementation of how you store your user data depends on your application
    const repo = new MyUserDataRepo();
    
    // Get reference to the currently signed-in user
    const auth = getAuth();
    const prevUser = auth.currentUser;
    
    // Get the data which you will want to merge. This should be done now
    // while the app is still signed in as this user.
    const prevUserData = repo.get(prevUser);
    
    // Delete the user's data now, we will restore it if the merge fails
    repo.delete(prevUser);
    
    // Sign in user with the account you want to link to
    signInWithCredential(auth, newCredential).then((result) => {
      console.log("Sign In Success", result);
      const currentUser = result.user;
      const currentUserData = repo.get(currentUser);
    
      // Merge prevUser and currentUser data stored in Firebase.
      // Note: How you handle this is specific to your application
      const mergedData = repo.merge(prevUserData, currentUserData);
    
      const credential = OAuthProvider.credentialFromResult(result);
      return linkWithCredential(prevUser, credential)
        .then((linkResult) => {
          // Sign in with the newly linked credential
          const linkCredential = OAuthProvider.credentialFromResult(linkResult);
          return signInWithCredential(auth, linkCredential);
        })
        .then((signInResult) => {
          // Save the merged data to the new user
          repo.set(signInResult.user, mergedData);
        });
    }).catch((error) => {
      // If there are errors we want to undo the data merge/deletion
      console.log("Sign In Error", error);
      repo.set(prevUser, prevUserData);
    });

    Web namespaced API

    // The implementation of how you store your user data depends on your application
    var repo = new MyUserDataRepo();
    
    // Get reference to the currently signed-in user
    var prevUser = auth.currentUser;
    
    // Get the data which you will want to merge. This should be done now
    // while the app is still signed in as this user.
    var prevUserData = repo.get(prevUser);
    
    // Delete the user's data now, we will restore it if the merge fails
    repo.delete(prevUser);
    
    // Sign in user with the account you want to link to
    auth.signInWithCredential(newCredential).then((result) => {
      console.log("Sign In Success", result);
      var currentUser = result.user;
      var currentUserData = repo.get(currentUser);
    
      // Merge prevUser and currentUser data stored in Firebase.
      // Note: How you handle this is specific to your application
      var mergedData = repo.merge(prevUserData, currentUserData);
    
      return prevUser.linkWithCredential(result.credential)
        .then((linkResult) => {
          // Sign in with the newly linked credential
          return auth.signInWithCredential(linkResult.credential);
        })
        .then((signInResult) => {
          // Save the merged data to the new user
          repo.set(signInResult.user, mergedData);
        });
    }).catch((error) => {
      // If there are errors we want to undo the data merge/deletion
      console.log("Sign In Error", error);
      repo.set(prevUser, prevUserData);
    });

若要將電子郵件地址和密碼憑證新增至現有使用者帳戶:

  1. 使用任何身份驗證提供者或方法登入使用者。
  2. 提示使用者輸入電子郵件地址和新密碼。
  3. 使用電子郵件地址和密碼建立AuthCredential物件:

    Web modular API

    import { EmailAuthProvider } from "firebase/auth";
    
    const credential = EmailAuthProvider.credential(email, password);

    Web namespaced API

    var credential = firebase.auth.EmailAuthProvider.credential(email, password);
  4. AuthCredential物件傳遞給登入使用者的linkWithCredential方法:

    Web modular API

    import { getAuth, linkWithCredential } from "firebase/auth";
    
    const auth = getAuth();
    linkWithCredential(auth.currentUser, credential)
      .then((usercred) => {
        const user = usercred.user;
        console.log("Account linking success", user);
      }).catch((error) => {
        console.log("Account linking error", error);
      });

    Web namespaced API

    auth.currentUser.linkWithCredential(credential)
      .then((usercred) => {
        var user = usercred.user;
        console.log("Account linking success", user);
      }).catch((error) => {
        console.log("Account linking error", error);
      });

    如果憑證已連結到另一個使用者帳戶,則對linkWithCredential呼叫將會失敗。在這種情況下,您必須根據您的應用程式合併帳戶和關聯資料(請參閱上面的範例)。

您可以取消身份驗證提供者與帳戶的鏈接,以便用戶無法再使用該提供者登入。

若要取消身份驗證提供者與使用者帳戶的鏈接,請將提供者 ID 傳遞給unlink方法。您可以從providerData屬性取得連結到使用者的驗證提供者的提供者ID。

Web modular API

import { getAuth, unlink } from "firebase/auth";

const auth = getAuth();
unlink(auth.currentUser, providerId).then(() => {
  // Auth provider unlinked from account
  // ...
}).catch((error) => {
  // An error happened
  // ...
});

Web namespaced API

user.unlink(providerId).then(() => {
  // Auth provider unlinked from account
  // ...
}).catch((error) => {
  // An error happened
  // ...
});