透過 JavaScript 使用 Google 驗證

您可以讓使用者使用自己的 Google 帳戶向 Firebase 進行驗證。 您可以使用 Firebase SDK 執行 Google 登入流程,或 使用「使用 Google 帳戶登入」程式庫手動執行登入流程,以及 再將產生的 ID 符記傳送至 Firebase。

事前準備

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

使用 Firebase SDK 處理登入流程

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

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

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

    Web

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

    Web

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

    Web

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

    Web

    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
    請參閱驗證供應商 說明文件
  3. 選用:根據使用者偏好的設定,將提供者的 OAuth 流程本地化 或者在不明確傳送相關自訂 OAuth 參數的情況下,更新 ,再啟動 OAuth 流程。例如:

    Web

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

    Web

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  4. 選用:指定其他自訂 OAuth 供應商參數 您傳送的 OAuth 要求部分。如要新增自訂參數,請呼叫 已初始化提供者的 setCustomParameters,其物件包含金鑰 如 OAuth 供應商說明文件所載,以及相應的值中。例如:

    Web

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

    Web

    provider.setCustomParameters({
      'login_hint': 'user@example.com'
    });
    系統不允許保留的必要 OAuth 參數,因此會予以忽略。 請參閱 驗證供應商參考資料瞭解更多資訊。
  5. 使用 Google 供應商物件向 Firebase 進行驗證。你可以 提示使用者開啟 彈出式視窗,或重新導向至登入頁面。重新導向方法是 在行動裝置上顯示。
    • 如要透過彈出式視窗登入,請呼叫 signInWithPopup

      Web

      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

      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」時,請遵循最佳做法

      Web

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

      Web

      firebase.auth().signInWithRedirect(provider);
      接著,您也可以呼叫 getRedirectResult

      Web

      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

      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 Realtime DatabaseCloud Storage中 查看安全性規則 透過 auth 變數取得已登入使用者的不重複使用者 ID。 控管使用者可以存取的資料

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

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

Web

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

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

Web

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