透過 GitHub 登入使用者

本文說明如何使用 Identity Platform,透過 GitHub 登入使用者帳戶。

事前準備

本教學課程假設您已啟用 Identity Platform,並使用 HTML 和 JavaScript 編寫基本網頁應用程式。如要瞭解操作方式,請參閱快速入門導覽課程

將 GitHub 設定為提供者

如要將 GitHub 設定為識別資訊提供者,請按照下列步驟操作:

  1. 前往 Google Cloud 控制台的「Identity Providers」(識別資訊提供者) 頁面。

    前往「Identity Providers」頁面

  2. 按一下「Add A Provider」

  3. 從清單中選取「GitHub」GitHub

  4. 輸入 GitHub 用戶端 ID用戶端密鑰。如果您尚未取得 ID 和密碼,可以前往 GitHub 應用程式頁面取得。

  5. 將「設定 GitHub」下方列出的 URI,設定為 GitHub 應用程式的有效 OAuth 重新導向 URI。如果您在 Identity Platform 中設定了自訂網域,請更新 GitHub 應用程式設定中的重新導向 URI,改用自訂網域而非預設網域。例如,將 https://myproject.firebaseapp.com/__/auth/handler 變更為 https://auth.myownpersonaldomain.com/__/auth/handler

  6. 按一下「已授權網域」下方的「新增網域」,註冊應用程式的網域。為方便開發,系統預設已啟用 localhost

  7. 在「設定應用程式」下方,按一下「設定詳細資料」。將程式碼片段複製到應用程式的程式碼中,初始化 Identity Platform 用戶端 SDK。

  8. 按一下 [儲存]

透過用戶端 SDK 登入使用者

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

    網頁版 9

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

    網頁版 8

    var provider = new firebase.auth.GithubAuthProvider();
  1. 選填:新增 OAuth 範圍。範圍會指定您向 GitHub 要求的資料。如要存取更敏感的資料,可能需要特定範圍。請參閱供應商的說明文件,判斷應用程式需要哪些範圍。

    網頁版 9

    provider.addScope('repo');

    網頁版 8

    provider.addScope('repo');
  1. 選用:將驗證流程在地化。你可以指定語言,或使用裝置的預設語言:

    網頁版 9

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

    網頁版 8

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  2. 選用:指定其他自訂 OAuth 參數。這些是 GitHub 專屬的範圍,通常用於自訂驗證體驗。您無法傳遞 OAuth 或 Identity Platform 保留的參數。

網頁版 9

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

網頁版 8

provider.setCustomParameters({
  'allow_signup': 'false'
});
  1. 使用 GitHub 供應商物件登入使用者。您可以開啟彈出式視窗,或重新導向目前頁面。行動裝置使用者更容易重新導向。

    如要顯示彈出式視窗,請呼叫 signInWithPopup()

    網頁版 9

    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);
        // ...
      });

    網頁版 8

    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;
        // ...
      });

    如要重新導向頁面,請先呼叫 signInWithRedirect()

    使用 signInWithRedirectlinkWithRedirectreauthenticateWithRedirect 時,請遵循最佳做法

    網頁版 9

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

    網頁版 8

    firebase.auth().signInWithRedirect(provider);

    然後,在網頁載入時呼叫 getRedirectResult(),即可擷取 GitHub 權杖:

    網頁版 9

    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);
        // ...
      });

    網頁版 8

    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;
        // ...
      });

取得存取權杖後,即可用來呼叫 GitHub API。 例如:

REST

curl -H "Authorization: Bearer [TOKEN]" https://api.github.com/gists/starred

手動登入使用者

如果不想使用用戶端 SDK,也可以手動處理登入流程:

  1. 按照 開發人員說明文件中的步驟,將 GitHub 驗證功能整合到應用程式中。

  2. 使用您在上一步中實作的流程,透過 GitHub 登入使用者。

  3. 將從 GitHub 收到的權杖換成 Identity Platform 憑證:

    網頁版 9

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

    網頁版 8

    var credential = firebase.auth.GithubAuthProvider.credential(token);
  4. 使用憑證透過 Identity Platform 登入使用者:

    網頁版 9

    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;
        // ...
      });

    網頁版 8

    // 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;
        // ...
      });

後續步驟