通過 JavaScript 使用 Google 進行身份驗證

您可以讓您的用戶使用他們的 Google 帳戶通過 Firebase 進行身份驗證。您可以使用 Firebase SDK 執行 Google 登錄流程,或者使用 Sign In With Google 庫手動執行登錄流程並將生成的 ID 令牌傳遞給 Firebase。

在你開始之前

  1. 將 Firebase 添加到您的 JavaScript 項目
  2. 在 Firebase 控制台中啟用 Google 作為登錄方法:
    1. Firebase 控制台中,打開Auth部分。
    2. 登錄方法選項卡上,啟用Google登錄方法並單擊保存

使用 Firebase SDK 處理登錄流程

如果您正在構建 Web 應用程序,使用用戶的 Google 帳戶通過 Firebase 對用戶進行身份驗證的最簡單方法是使用 Firebase JavaScript SDK 處理登錄流程。 (如果您想在 Node.js 或其他非瀏覽器環境中對用戶進行身份驗證,則必須手動處理登錄流程。)

要使用 Firebase JavaScript SDK 處理登錄流程,請執行以下步驟:

  1. 創建 Google 提供者對象的實例:

    Web modular API

    import { GoogleAuthProvider } from "firebase/auth";
    
    const provider = new GoogleAuthProvider();

    Web namespaced API

    var provider = new firebase.auth.GoogleAuthProvider();
  2. 可選:指定您要從身份驗證提供程序請求的其他 OAuth 2.0 範圍。要添加範圍,請調用addScope 。例如:

    Web modular API

    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');

    Web namespaced API

    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
    請參閱身份驗證提供程序文檔
  3. 可選:要將提供商的 OAuth 流程本地化為用戶的首選語言而不顯式傳遞相關的自定義 OAuth 參數,請在啟動 OAuth 流程之前更新 Auth 實例上的語言代碼。例如:

    Web modular API

    import { getAuth } from "firebase/auth";
    
    const auth = getAuth();
    auth.languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();

    Web namespaced API

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  4. 可選:指定要與 OAuth 請求一起發送的其他自定義 OAuth 提供程序參數。要添加自定義參數,請使用包含 OAuth 提供程序文檔指定的密鑰和相應值的對像對已初始化的提供程序調用setCustomParameters 。例如:

    Web modular API

    provider.setCustomParameters({
      'login_hint': 'user@example.com'
    });

    Web namespaced API

    provider.setCustomParameters({
      'login_hint': 'user@example.com'
    });
    保留的必需 OAuth 參數是不允許的,將被忽略。有關更多詳細信息,請參閱身份驗證提供程序參考
  5. 使用 Google 提供商對象通過 Firebase 進行身份驗證。您可以通過打開彈出窗口或重定向到登錄頁面來提示您的用戶使用他們的 Google 帳戶登錄。在移動設備上首選重定向方法。
    • 要使用彈出窗口登錄,請調用signInWithPopup

      Web modular API

      import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      signInWithPopup(auth, provider)
        .then((result) => {
          // This gives you a Google Access Token. You can use it to access the Google API.
          const credential = GoogleAuthProvider.credentialFromResult(result);
          const token = credential.accessToken;
          // The signed-in user info.
          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;
          // The AuthCredential type that was used.
          const credential = GoogleAuthProvider.credentialFromError(error);
          // ...
        });

      Web namespaced API

      firebase.auth()
        .signInWithPopup(provider)
        .then((result) => {
          /** @type {firebase.auth.OAuthCredential} */
          var credential = result.credential;
      
          // This gives you a Google Access Token. You can use it to access the Google 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;
          // ...
        });
      另請注意,您可以檢索 Google 提供商的 OAuth 令牌,該令牌可用於使用 Google API 獲取其他數據。

      這也是您可以捕獲和處理錯誤的地方。有關錯誤代碼的列表,請查看Auth Reference Docs

    • 要通過重定向到登錄頁面登錄,請調用signInWithRedirect :使用 signInWithRedirect 時遵循最佳實踐

      Web modular API

      import { getAuth, signInWithRedirect } from "firebase/auth";
      
      const auth = getAuth();
      signInWithRedirect(auth, provider);

      Web namespaced API

      firebase.auth().signInWithRedirect(provider);
      然後,您還可以通過在頁面加載時調用getRedirectResult來檢索 Google 提供商的 OAuth 令牌:

      Web modular API

      import { getAuth, getRedirectResult, GoogleAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      getRedirectResult(auth)
        .then((result) => {
          // This gives you a Google Access Token. You can use it to access Google APIs.
          const credential = GoogleAuthProvider.credentialFromResult(result);
          const token = credential.accessToken;
      
          // The signed-in user info.
          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;
          // The AuthCredential type that was used.
          const credential = GoogleAuthProvider.credentialFromError(error);
          // ...
        });

      Web namespaced API

      firebase.auth()
        .getRedirectResult()
        .then((result) => {
          if (result.credential) {
            /** @type {firebase.auth.OAuthCredential} */
            var credential = result.credential;
      
            // This gives you a Google Access Token. You can use it to access the Google 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;
          // ...
        });
      這也是您可以捕獲和處理錯誤的地方。有關錯誤代碼的列表,請查看Auth Reference Docs

在 Chrome 擴展程序中使用 Firebase 進行身份驗證

如果您正在構建 Chrome 擴展應用,則必須添加您的 Chrome 擴展 ID:

  1. Firebase 控制台中打開您的項目。
  2. 身份驗證部分中,打開登錄方法頁面。
  3. 將如下所示的 URI 添加到授權域列表中:
    chrome-extension://CHROME_EXTENSION_ID

只有彈出操作( signInWithPopuplinkWithPopupreauthenticateWithPopup )可用於 Chrome 擴展,因為 Chrome 擴展不能使用 HTTP 重定向。您應該從後台頁面腳本而不是瀏覽器操作彈出窗口調用這些方法,因為身份驗證彈出窗口將取消瀏覽器操作彈出窗口。彈出方法只能在使用Manifest V2 的擴展中使用。較新的Manifest V3只允許以 service workers 的形式運行後台腳本,根本無法執行彈窗操作。

在 Chrome 擴展程序的清單文件中,確保將https://apis.google.com URL 添加到content_security_policy白名單。

下一步

用戶首次登錄後,將創建一個新的用戶帳戶並將其鏈接到用戶登錄所用的憑據,即用戶名和密碼、電話號碼或身份驗證提供商信息。這個新帳戶存儲為您的 Firebase 項目的一部分,可用於在項目中的每個應用程序中識別用戶,無論用戶如何登錄。

  • 在您的應用程序中,了解用戶身份驗證狀態的推薦方法是在Auth對像上設置觀察者。然後,您可以從User對像中獲取用戶的基本個人資料信息。請參閱管理用戶

  • 在您的 Firebase Realtime Database 和 Cloud Storage Security Rules中,您可以從auth變量中獲取登錄用戶的唯一用戶 ID,並使用它來控制用戶可以訪問哪些數據。

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

要註銷用戶,請調用signOut

Web modular API

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

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

Web namespaced API

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