透過 Google 登入使用者

本文說明如何使用 Identity Platform,讓使用者透過 Google 登入。

事前準備

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

將 Google 設定為提供者

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

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

    前往「Identity Providers」(識別資訊提供者) 頁面

  2. 按一下「Add A Provider」
  3. 從清單中選取「Google」
  4. 輸入 Google 網頁用戶端 ID網頁密鑰。 如果還沒有 ID 和密鑰,可以從「API 和服務」頁面取得。
  5. 如要允許透過外部用戶端 ID 存取,請按一下「新增」,然後新增用戶端 ID。
  6. 如要設定同意畫面,請按一下「設定畫面」。「Google Auth Platform」頁面會在另一個分頁中開啟。
  7. 在「Google Auth Platform」(Google 驗證平台) 頁面中, 設定 OAuth 同意畫面
  8. 返回「身分識別供應商」頁面,在「專案設定」側邊窗格中,按一下「新增網域」,然後新增應用程式的網域。

    建議您不要在正式版專案中加入 localhost

  9. 在「設定應用程式」部分,按一下「設定詳細資料」。將程式碼片段複製到應用程式的程式碼中,初始化 Identity Platform 用戶端 SDK。
  10. 按一下 [儲存]

使用用戶端 SDK 登入使用者

  1. 建立 Google 供應商物件的執行個體:

    網頁版 9

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

    網頁版 8

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

    網頁版 9

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

    網頁版 8

    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
  3. 選用:將驗證流程在地化。你可以指定語言,或使用裝置的預設語言:

    網頁版 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();
  4. 選用:指定其他自訂 OAuth 參數。這些參數是 Google 專屬參數,通常用於自訂驗證體驗。您無法傳遞 OAuth 或 Identity Platform 保留的參數。

    網頁版 9

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

    網頁版 8

    provider.setCustomParameters({
      'login_hint': 'user@example.com'
    });
  5. 使用 Google 提供者物件登入使用者。您可以開啟彈出式視窗,或重新導向目前頁面。行動裝置使用者更容易重新導向。

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

    網頁版 9

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

    網頁版 8

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

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

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

    網頁版 9

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

    網頁版 8

    firebase.auth().signInWithRedirect(provider);

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

    網頁版 9

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

    網頁版 8

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

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

REST

curl -H "Authorization: Bearer [TOKEN]" https://www.googleapis.com/oauth2/v2/userinfo

手動登入使用者

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

  1. 按照開發人員說明文件中的步驟,將 Google 驗證功能整合至應用程式。
  2. 使用您在上一步中實作的流程,透過 Google 登入使用者帳戶。
  3. 將從 Google 收到的權杖換成 Identity Platform 憑證:

    網頁版 9

    import { GoogleAuthProvider } from "firebase/auth";
    
    const credential = GoogleAuthProvider.credential(idToken);

    網頁版 8

    var credential = firebase.auth.GoogleAuthProvider.credential(idToken);
  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;
        // ...
      });

後續步驟