以 JavaScript 使用 Facebook 登入進行驗證

您可以讓使用者利用 Facebook 帳戶向 Firebase 進行驗證 整合 Facebook 登入應用程式。您可以整合 Facebook 登入 或透過 Firebase SDK 執行登入流程 手動送出 Facebook 登入流程,並將產生的存取權杖傳遞至 Firebase。

事前準備

  1. 將 Firebase 新增至您的 JavaScript 專案
  2. Facebook for Developers 上 網站,請取得應用程式的「應用程式 ID」和「應用程式密鑰」。
  3. 啟用 Facebook 登入:
    1. Firebase 控制台中開啟「Auth」專區。
    2. 在「Sign in method」分頁中,啟用 Facebook 登入功能 方法,並指定您從 Facebook 取得的「應用程式 ID」和「應用程式密鑰」
    3. 接著,請確認您的 OAuth 重新導向 URI (例如 my-app-12345.firebaseapp.com/__/auth/handler) 是您 Facebook 應用程式設定頁面的其中一個 OAuth 重新導向 URIFacebook for Developers 網站 產品設定 >Facebook Login 設定。

使用 Firebase SDK 處理登入流程

如要建構網頁應用程式,驗證使用者最簡單的方法 使用 Facebook 帳戶處理登入流程 Firebase JavaScript SDK(如果您要在 Node.js 驗證使用者 或其他非瀏覽器環境,您必須手動處理登入流程)。

如要使用 Firebase JavaScript SDK 處理登入流程,請按照下列步驟操作: 步驟:

  1. 建立 Facebook 提供者物件的例項:
    WebWeb
    import { FacebookAuthProvider } from "firebase/auth";
    
    const provider = new FacebookAuthProvider();
    var provider = new firebase.auth.FacebookAuthProvider();
  2. 選用:指定您打算的其他 OAuth 2.0 範圍 要求驗證服務供應商如要新增範圍,請呼叫 addScope。例如:
    WebWeb
    provider.addScope('user_birthday');
    provider.addScope('user_birthday');
    請參閱驗證供應商 說明文件
  3. 選用:根據使用者偏好的設定,將提供者的 OAuth 流程本地化 或者在不明確傳送相關自訂 OAuth 參數的情況下,更新 ,再啟動 OAuth 流程。例如:
    WebWeb
    import { getAuth } from "firebase/auth";
    
    const auth = getAuth();
    auth.languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // auth.useDeviceLanguage();
    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  4. 選用:指定其他自訂 OAuth 供應商參數 您傳送的 OAuth 要求部分。如要新增自訂參數,請呼叫 已初始化提供者的 setCustomParameters,其物件包含金鑰 如 OAuth 供應商說明文件所載,以及相應的值中。例如:
    WebWeb
    provider.setCustomParameters({
      'display': 'popup'
    });
    provider.setCustomParameters({
      'display': 'popup'
    });
    系統不允許保留的必要 OAuth 參數,因此會予以忽略。 請參閱 驗證供應商參考資料瞭解更多資訊。
  5. 使用 Facebook 提供者物件,向 Firebase 進行驗證。你可以 提示使用者透過 彈出式視窗,或重新導向至登入頁面。重新導向方法是 在行動裝置上顯示。
    • 如要透過彈出式視窗登入,請呼叫 signInWithPopup
      WebWeb
      import { getAuth, signInWithPopup, FacebookAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      signInWithPopup(auth, provider)
        .then((result) => {
          // The signed-in user info.
          const user = result.user;
      
          // This gives you a Facebook Access Token. You can use it to access the Facebook API.
          const credential = FacebookAuthProvider.credentialFromResult(result);
          const accessToken = credential.accessToken;
      
          // IdP data available using getAdditionalUserInfo(result)
          // ...
        })
        .catch((error) => {
          // Handle Errors here.
          const errorCode = error.code;
          const errorMessage = error.message;
          // The email of the user's account used.
          const email = error.customData.email;
          // The AuthCredential type that was used.
          const credential = FacebookAuthProvider.credentialFromError(error);
      
          // ...
        });
      firebase
        .auth()
        .signInWithPopup(provider)
        .then((result) => {
          /** @type {firebase.auth.OAuthCredential} */
          var credential = result.credential;
      
          // The signed-in user info.
          var user = result.user;
          // IdP data available in result.additionalUserInfo.profile.
            // ...
      
          // This gives you a Facebook Access Token. You can use it to access the Facebook API.
          var accessToken = credential.accessToken;
      
          // ...
        })
        .catch((error) => {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
      
          // ...
        });
      另請注意,您可以擷取 Facebook 提供者的 OAuth 符記,以便透過 Facebook API 擷取其他資料。

      您也能在這裡找出並處理錯誤。如需錯誤代碼清單,請參閱驗證參考文件

    • 如要重新導向至登入頁面,請呼叫 signInWithRedirect: 使用「signInWithRedirect」時,請遵循最佳做法
      WebWeb
      import { getAuth, signInWithRedirect } from "firebase/auth";
      
      const auth = getAuth();
      signInWithRedirect(auth, provider);
      firebase.auth().signInWithRedirect(provider);
      接著,您也可以呼叫 getRedirectResult
      WebWeb
      import { getAuth, getRedirectResult, FacebookAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      getRedirectResult(auth)
        .then((result) => {
          // This gives you a Facebook Access Token. You can use it to access the Facebook API.
          const credential = FacebookAuthProvider.credentialFromResult(result);
          const token = credential.accessToken;
      
          const user = result.user;
          // IdP data available using getAdditionalUserInfo(result)
          // ...
        }).catch((error) => {
          // Handle Errors here.
          const errorCode = error.code;
          const errorMessage = error.message;
          // The email of the user's account used.
          const email = error.customData.email;
          // AuthCredential type that was used.
          const credential = FacebookAuthProvider.credentialFromError(error);
          // ...
        });
      firebase.auth()
        .getRedirectResult()
        .then((result) => {
          if (result.credential) {
            /** @type {firebase.auth.OAuthCredential} */
            var credential = result.credential;
      
            // This gives you a Facebook Access Token. You can use it to access the Facebook API.
            var token = credential.accessToken;
            // ...
          }
          // The signed-in user info.
          var user = result.user;
          // IdP data available in result.additionalUserInfo.profile.
            // ...
        }).catch((error) => {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
          // ...
        });
      您也能在這裡找出並處理錯誤。如需錯誤代碼清單,請參閱驗證參考文件
,瞭解如何調查及移除這項存取權。

如果您已在 Firebase 控制台中啟用「每個電子郵件地址一個帳戶」設定: 使用者嘗試使用現有的電子郵件地址登入供應商 (例如 Facebook) 時 也存在於其他 Firebase 使用者的供應商 (例如 Google) 中,因此發生錯誤 auth/account-exists-with-different-credential 會與 AuthCredential 物件 (Facebook 存取權杖)。如要完成 使用者必須先登入現有的供應商 (Google),才能連結至 先前的 AuthCredential (Facebook 存取權杖)。

如果使用 signInWithPopup,您就可以處理 有 auth/account-exists-with-different-credential 個錯誤,且程式碼如下所示 範例:

import {
  getAuth,
  linkWithCredential,
  signInWithPopup,
  FacebookAuthProvider,
} from "firebase/auth";

try {
  // Step 1: User tries to sign in using Facebook.
  let result = await signInWithPopup(getAuth(), new FacebookAuthProvider());
} catch (error) {
  // Step 2: User's email already exists.
  if (error.code === "auth/account-exists-with-different-credential") {
    // The pending Facebook credential.
    let pendingCred = error.credential;

    // Step 3: Save the pending credential in temporary storage,

    // Step 4: Let the user know that they already have an account
    // but with a different provider, and let them choose another
    // sign-in method.
  }
}

// ...

try {
  // Step 5: Sign the user in using their chosen method.
  let result = await signInWithPopup(getAuth(), userSelectedProvider);

  // Step 6: Link to the Facebook credential.
  // TODO: implement `retrievePendingCred` for your app.
  let pendingCred = retrievePendingCred();

  if (pendingCred !== null) {
    // As you have access to the pending credential, you can directly call the
    // link method.
    let user = await linkWithCredential(result.user, pendingCred);
  }

  // Step 7: Continue to app.
} catch (error) {
  // ...
}

重新導向模式

這項錯誤的處理方式與重新導向模式下相同,但有差異 憑證必須在網頁重新導向之間快取 (例如使用工作階段儲存空間)。

您也可以使用 Facebook 帳戶,向 Firebase 進行驗證,方法是將 使用 Facebook Login JavaScript SDK 登入流程:

  1. 遵循下列步驟,將 Facebook 登入整合至應用程式: 開發人員文件。 請務必使用您的 Facebook 應用程式 ID 設定 Facebook 登入:
    <script src="//connect.facebook.net/en_US/sdk.js"></script>
    <script>
      FB.init({
        /**********************************************************************
         * TODO(Developer): Change the value below with your Facebook app ID. *
         **********************************************************************/
        appId: '<YOUR_FACEBOOK_APP_ID>',
        status: true,
        xfbml: true,
        version: 'v2.6',
      });
    </script>
  2. 我們也會在 Facebook 驗證狀態上設定監聽器:
    FB.Event.subscribe('auth.authResponseChange', checkLoginState);
  3. 整合 Facebook 登入之後,請在您的網頁中加入 Facebook 登入按鈕:
    <fb:login-button
      data-auto-logout-link="true"
      scope="public_profile,email"
      size="large"
    ></fb:login-button>
  4. 在 Facebook 驗證狀態回呼中,交換來自 Facebook 驗證回應的驗證權杖,以取得 Firebase 憑證並登入 Firebase:
    WebWeb
    import { getAuth, onAuthStateChanged, signInWithCredential, signOut, FacebookAuthProvider } from "firebase/auth";
    const auth = getAuth();
    
    function checkLoginState(response) {
      if (response.authResponse) {
        // User is signed-in Facebook.
        const unsubscribe = onAuthStateChanged(auth, (firebaseUser) => {
          unsubscribe();
          // Check if we are already signed-in Firebase with the correct user.
          if (!isUserEqual(response.authResponse, firebaseUser)) {
            // Build Firebase credential with the Facebook auth token.
            const credential = FacebookAuthProvider.credential(
                response.authResponse.accessToken);
    
            // Sign in with the credential from the Facebook user.
            signInWithCredential(auth, credential)
              .catch((error) => {
                // Handle Errors here.
                const errorCode = error.code;
                const errorMessage = error.message;
                // The email of the user's account used.
                const email = error.customData.email;
                // The AuthCredential type that was used.
                const credential = FacebookAuthProvider.credentialFromError(error);
                // ...
              });
          } else {
            // User is already signed-in Firebase with the correct user.
          }
        });
      } else {
        // User is signed-out of Facebook.
        signOut(auth);
      }
    }
    function checkLoginState(response) {
      if (response.authResponse) {
        // User is signed-in Facebook.
        var unsubscribe = firebase.auth().onAuthStateChanged((firebaseUser) => {
          unsubscribe();
          // Check if we are already signed-in Firebase with the correct user.
          if (!isUserEqual(response.authResponse, firebaseUser)) {
            // Build Firebase credential with the Facebook auth token.
            var credential = firebase.auth.FacebookAuthProvider.credential(
                response.authResponse.accessToken);
    
            // Sign in with the credential from the Facebook user.
            firebase.auth().signInWithCredential(credential)
              .catch((error) => {
                // Handle Errors here.
                var errorCode = error.code;
                var errorMessage = error.message;
                // The email of the user's account used.
                var email = error.email;
                // The firebase.auth.AuthCredential type that was used.
                var credential = error.credential;
                // ...
              });
          } else {
            // User is already signed-in Firebase with the correct user.
          }
        });
      } else {
        // User is signed-out of Facebook.
        firebase.auth().signOut();
      }
    }
    您也能在這裡找出並處理錯誤。如需錯誤代碼清單,請參閱驗證參考文件
  5. 此外,請檢查 Facebook 使用者是否已登入 Firebase,以免不需要重新驗證:
    WebWeb
    import { FacebookAuthProvider } from "firebase/auth";
    
    function isUserEqual(facebookAuthResponse, firebaseUser) {
      if (firebaseUser) {
        const providerData = firebaseUser.providerData;
        for (let i = 0; i < providerData.length; i++) {
          if (providerData[i].providerId === FacebookAuthProvider.PROVIDER_ID &&
              providerData[i].uid === facebookAuthResponse.userID) {
            // We don't need to re-auth the Firebase connection.
            return true;
          }
        }
      }
      return false;
    }
    function isUserEqual(facebookAuthResponse, firebaseUser) {
      if (firebaseUser) {
        var providerData = firebaseUser.providerData;
        for (var i = 0; i < providerData.length; i++) {
          if (providerData[i].providerId === firebase.auth.FacebookAuthProvider.PROVIDER_ID &&
              providerData[i].uid === facebookAuthResponse.userID) {
            // We don't need to re-auth the Firebase connection.
            return true;
          }
        }
      }
      return false;
    }

如要在 Node.js 應用程式中使用 Firebase 進行驗證:

  1. 透過 Facebook 帳戶登入使用者,並取得對方的 Facebook 存取權杖例如,按照 處理登入 手動流程區段,但請將存取權杖傳送至 Node.js 而不是在用戶端應用程式中使用
  2. 取得使用者的 Facebook 存取權杖後,請使用該權杖建立 憑證物件,然後以憑證登入使用者:
    WebWeb
    import { getAuth, signInWithCredential, FacebookAuthProvider } from "firebase/auth";
    
    // Sign in with the credential from the Facebook user.
    const auth = getAuth();
    signInWithCredential(auth, credential)
      .then((result) => {
        // Signed in 
        const credential = FacebookAuthProvider.credentialFromResult(result);
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.customData.email;
        // The AuthCredential type that was used.
        const credential = FacebookAuthProvider.credentialFromError(error);
        // ...
      });
    // Sign in with the credential from the Facebook user.
    firebase.auth().signInWithCredential(credential)
      .then((result) => {
        // Signed in       
        var credential = result.credential;
        // ...
      })
      .catch((error) => {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // ...
      });

在 Chrome 擴充功能中使用 Firebase 驗證

如果您要建立 Chrome 擴充功能應用程式,請參閱 螢幕外文件指南

建立專案時,Firebase 會為您的專案佈建一個專屬的子網域: https://my-app-12345.firebaseapp.com

這也會用來做為 OAuth 登入的重新導向機制。網域 允許所有支援的 OAuth 供應商。不過,這表示使用者可能會看到 網域,再重新重新導向應用程式: 繼續前往:https://my-app-12345.firebaseapp.com

如要避免顯示子網域,你可以使用 Firebase Hosting 設定自訂網域:

  1. 按照以下步驟 1 到 3: Hosting 設定網域。完成驗證後的影響 您的網域擁有權,Hosting 會為自訂網域佈建 SSL 憑證。
  2. 將自訂網域新增至 Firebase 控制台auth.custom.domain.com
  3. 在 Facebook 開發人員主控台或 OAuth 設定頁面,將重新導向網頁的網址加入許可清單。 將可在自訂網域上存取: https://auth.custom.domain.com/__/auth/handler
  4. 初始化 JavaScript 程式庫時,請使用 authDomain 欄位:
    var config = {
      apiKey: '...',
      // Changed from 'PROJECT_ID.firebaseapp.com'.
      authDomain: 'auth.custom.domain.com',
      databaseURL: 'https://PROJECT_ID.firebaseio.com',
      projectId: 'PROJECT_ID',
      storageBucket: 'PROJECT_ID.firebasestorage.app',
      messagingSenderId: 'SENDER_ID'
    };
    firebase.initializeApp(config);

後續步驟

使用者首次登入後,系統會建立新的使用者帳戶 也就是使用者的名稱和密碼 號碼或驗證提供者資訊,也就是使用者登入時使用的網址。這項新功能 帳戶儲存為 Firebase 專案的一部分,可用來識別 即可限制使用者登入專案中的所有應用程式

  • 在應用程式中得知使用者的驗證狀態,建議做法是 在 Auth 物件上設定觀察器。接著,您就能取得使用者的 User 物件的基本個人資料資訊。詳情請見 管理使用者

  • 在你的Firebase Realtime DatabaseCloud Storage中 查看安全性規則 透過 auth 變數取得已登入使用者的不重複使用者 ID。 控管使用者可以存取的資料

您可以讓使用者透過多重驗證機制登入您的應用程式 將驗證供應商憑證連結至 現有的使用者帳戶

如要登出使用者,請呼叫 signOut

WebWeb
import { getAuth, signOut } from "firebase/auth";

const auth = getAuth();
signOut(auth).then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});
firebase.auth().signOut().then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});