使用 GitHub 和 JavaScript 進行身份驗證

透過將 GitHub 驗證整合到您的應用程式中,您可以讓使用者使用其 GitHub 帳戶透過 Firebase 進行身份驗證。您可以透過使用 Firebase SDK 執行登入流程,或手動執行 GitHub OAuth 2.0 流程並將產生的存取權杖傳遞給 Firebase 來整合 GitHub 驗證。

在你開始之前

  1. 將 Firebase 新增到您的 JavaScript 專案
  2. Firebase 控制台中,開啟「驗證」部分。
  3. 登入方法標籤上,啟用GitHub提供者。
  4. 客戶端 ID客戶端金鑰從該提供者的開發人員控制台新增至提供者設定:
    1. 在 GitHub上將您的應用程式註冊為開發人員應用程序,並獲取您的應用程式的 OAuth 2.0 Client IDClient Secret
    2. 確保您的 Firebase OAuth 重定向 URI (例如my-app-12345.firebaseapp.com/__/auth/handler )在GitHub 應用程式 config 的應用程式設定頁面中設定為您的授權回調 URL
  5. 按一下「儲存」

使用 Firebase SDK 處理登入流程

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

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

  1. 建立 GitHub 提供者物件的實例:

    Web modular API

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

    Web namespaced API

    var provider = new firebase.auth.GithubAuthProvider();
  2. 選用:指定您想要從身分驗證提供者要求的其他 OAuth 2.0 範圍。若要新增範圍,請呼叫addScope 。例如:

    Web modular API

    provider.addScope('repo');

    Web namespaced API

    provider.addScope('repo');
    請參閱身份驗證提供者文件
  3. 可選:指定要與 OAuth 請求一起傳送的其他自訂 OAuth 提供者參數。若要新增自訂參數,請使用包含 OAuth 提供者文件指定的鍵和對應值的物件對初始化的提供者呼叫setCustomParameters 。例如:

    Web modular API

    provider.setCustomParameters({
      'allow_signup': 'false'
    });

    Web namespaced API

    provider.setCustomParameters({
      'allow_signup': 'false'
    });
    不允許保留所需的 OAuth 參數,這些參數將被忽略。有關更多詳細信息,請參閱身份驗證提供者參考
  4. 使用 GitHub 提供者物件透過 Firebase 進行身份驗證。您可以透過開啟彈出視窗或重定向到登入頁面來提示使用者使用其 GitHub 帳戶登入。重定向方法在行動裝置上是首選。
    • 若要使用彈出視窗登錄,請呼叫signInWithPopup

      Web modular API

      import { getAuth, signInWithPopup, GithubAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      signInWithPopup(auth, provider)
        .then((result) => {
          // This gives you a GitHub Access Token. You can use it to access the GitHub API.
          const credential = GithubAuthProvider.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 = GithubAuthProvider.credentialFromError(error);
          // ...
        });

      Web namespaced API

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

      Web modular API

      import { getAuth, getRedirectResult, GithubAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      getRedirectResult(auth)
        .then((result) => {
          const credential = GithubAuthProvider.credentialFromResult(result);
          if (credential) {
            // This gives you a GitHub Access Token. You can use it to access the GitHub API.
            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 = GithubAuthProvider.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 GitHub Access Token. You can use it to access the GitHub 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

手動處理登入流程

您也可以透過呼叫 GitHub OAuth 2.0 端點處理登入流程,使用 GitHub 帳戶向 Firebase 進行驗證:

  1. 依照開發人員文件將 GitHub 驗證整合到您的應用程式中。在 GitHub 登入流程結束時,您將收到 OAuth 2.0 存取權杖。
  2. 如果您需要登入 Node.js 應用程序,請將 OAuth 存取權杖發送到 Node.js 應用程式。
  3. 使用者成功登入 GitHub 後,將 OAuth 2.0 存取權杖交換為 Firebase 憑證:

    Web modular API

    import { GithubAuthProvider } from "firebase/auth";
    
    const credential = GithubAuthProvider.credential(token);

    Web namespaced API

    var credential = firebase.auth.GithubAuthProvider.credential(token);
  4. 使用 Firebase 憑證進行 Firebase 驗證:

    Web modular API

    import { getAuth, signInWithCredential } from "firebase/auth";
    
    // Sign in with the credential from the user.
    const auth = getAuth();
    signInWithCredential(auth, credential)
      .then((result) => {
        // Signed in 
        // ...
      })
      .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;
        // ...
      });

    Web namespaced API

    // Sign in with the credential from the user.
    firebase.auth()
      .signInWithCredential(credential)
      .then((result) => {
        // Signed in 
        // ...
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // ...
      });

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

如果您正在建立 Chrome 擴充功能應用程序,請參閱Offscreen Documents 指南

下一步

使用者首次登入後,系統會建立新的使用者帳戶,並將其連結到使用者登入時所使用的憑證(即使用者名稱和密碼、電話號碼或驗證提供者資訊)。此新帳戶將作為 Firebase 專案的一部分存儲,並且可用於識別專案中每個應用程式中的用戶,無論用戶如何登入。

  • 在您的應用程式中,了解使用者的身份驗證狀態的建議方法是在Auth物件上設定觀察者。然後,您可以從User物件取得使用者的基本個人資料資訊。請參閱管理用戶

  • 在 Firebase 即時資料庫和雲端儲存安全性規則中,您可以從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.
});