透過 JavaScript 使用 Google 驗證

您可以讓使用者使用自己的 Google 帳戶,透過 Firebase 進行驗證。您可以使用 Firebase SDK 執行 Google 登入流程,也可以使用「使用 Google 帳戶登入」程式庫,手動完成登入流程,並將產生的 ID 權杖傳遞至 Firebase。

事前準備

  1. 將 Firebase 新增至您的 JavaScript 專案
  2. 在 Firebase 控制台中啟用 Google 做為登入方式:
    1. Firebase 控制台開啟「驗證」專區。
    2. 在「Sign in method」分頁中啟用「Google」登入方式,然後按一下「Save」

使用 Firebase SDK 處理登入流程

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

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

  1. 建立 Google 提供者物件的執行個體:

    網頁模組 API

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

    網路命名空間 API

    var provider = new firebase.auth.GoogleAuthProvider();
  2. 選用:指定您要向驗證供應商要求的其他 OAuth 2.0 範圍。如要新增範圍,請呼叫 addScope。例如:

    網頁模組 API

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

    網路命名空間 API

    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
    請參閱驗證供應商說明文件
  3. 選用:如要將提供者的 OAuth 流程本地化到使用者偏好的語言,但不明確傳遞相關的自訂 OAuth 參數,請先更新驗證執行個體上的語言代碼,再啟動 OAuth 流程。例如:

    網頁模組 API

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

    網路命名空間 API

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  4. 選用:指定要與 OAuth 要求一起傳送的其他自訂 OAuth 供應商參數。如要新增自訂參數,請在已初始化的提供者上呼叫 setCustomParameters,並使用包含 OAuth 供應商說明文件指定的金鑰和對應值的物件。例如:

    網頁模組 API

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

    網路命名空間 API

    provider.setCustomParameters({
      'login_hint': 'user@example.com'
    });
    系統不允許保留的必要 OAuth 參數,因此會遭到忽略。詳情請參閱 驗證供應商參考資料
  5. 使用 Google 供應商物件向 Firebase 進行驗證。您可以開啟彈出式視窗或重新導向至登入頁面,提示使用者登入自己的 Google 帳戶。建議在行動裝置上使用重新導向方法。
    • 如要在彈出式視窗中登入,請呼叫 signInWithPopup

      網頁模組 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);
          // ...
        });

      網路命名空間 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 擷取其他資料。

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

    • 如要重新導向至登入頁面,請呼叫 signInWithRedirect:使用「signInWithRedirect」時,請按照最佳做法操作。

      網頁模組 API

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

      網路命名空間 API

      firebase.auth().signInWithRedirect(provider);
      接著,您也可以在網頁載入時呼叫 getRedirectResult,擷取 Google 供應商的 OAuth 權杖:

      網頁模組 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);
          // ...
        });

      網路命名空間 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;
          // ...
        });
      您也能在這裡找出並處理錯誤。如需錯誤代碼清單,請參閱驗證參考文件

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

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

後續步驟

使用者首次登入時,系統會建立新的使用者帳戶,並連結至憑證 (即使用者名稱與密碼、電話號碼或驗證提供者資訊),也就是使用者登入時使用的憑證。這個新帳戶會儲存在您的 Firebase 專案中,可用來識別專案中各個應用程式的使用者 (無論使用者登入方式為何)。

  • 如要在應用程式中瞭解使用者的驗證狀態,建議在 Auth 物件上設定觀察器。接著,您就能從 User 物件取得使用者的基本個人資料資訊。請參閱管理使用者一文。

  • 在 Firebase 即時資料庫和 Cloud Storage 安全性規則中,您可以透過 auth 變數取得登入使用者的專屬 ID,並使用該 ID 控管使用者可存取哪些資料。

您可以將驗證供應商憑證連結至現有的使用者帳戶,讓使用者透過多個驗證服務提供者登入您的應用程式。

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

網頁模組 API

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

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

網路命名空間 API

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