將 Google 登入整合至網頁應用程式

Google 登入會管理 OAuth 2.0 流程和權杖生命週期,可簡化與 Google API 的整合作業。使用者隨時可以撤銷應用程式的存取權

本文件將說明如何完成基本的 Google 登入整合。

建立授權憑證

任何使用 OAuth 2.0 存取 Google API 的應用程式都必須具備授權憑證,可用來向 Google 的 OAuth 2.0 伺服器識別該應用程式。下列步驟說明如何為專案建立憑證。如此一來,應用程式就能使用憑證存取您為該專案啟用的 API。

  1. Go to the Credentials page.
  2. 按一下 [Create credentials] (建立憑證) > [OAuth client ID] (OAuth 用戶端 ID)
  3. 選取「Web application」(網頁應用程式) 應用程式類型。
  4. 為 OAuth 2.0 用戶端命名,然後按一下「Create」(建立)

設定完畢後,請記下建立的用戶端 ID。 您需要用戶端 ID 才能完成後續步驟。(系統也會建立用戶端密鑰,但您只需要將密鑰用於伺服器端作業)。

載入 Google 平台資料庫

您必須在整合 Google 登入功能的網頁上加入 Google Platform 程式庫。

<script src="https://apis.google.com/js/platform.js" async defer></script>

指定應用程式的用戶端 ID

使用 google-signin-client_id 中繼資料元素,指定您在 Google Developers Console 中為應用程式建立的用戶端 ID。

<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">

新增 Google 登入按鈕

如要在網站中加入 Google 登入按鈕,最簡單的方法就是使用自動顯示的登入按鈕。只要編寫幾行程式碼,即可新增按鈕,讓其本身自動設定為針對使用者登入狀態和您要求的範圍,提供適當的文字、標誌和顏色。

如要建立使用預設設定的 Google 登入按鈕,請在登入頁面新增類別為 g-signin2div 元素:

<div class="g-signin2" data-onsuccess="onSignIn"></div>

取得個人資料

使用預設範圍登入 Google 使用者後,您就能存取使用者的 Google ID、名稱、個人資料網址和電子郵件地址。

如要擷取使用者的設定檔資訊,請使用 getBasicProfile() 方法。

function onSignIn(googleUser) {
  var profile = googleUser.getBasicProfile();
  console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
  console.log('Name: ' + profile.getName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
}

將使用者登出

您可以在網站中加入登出按鈕或連結,讓使用者不必登出 Google 就能登出應用程式。如要建立登出連結,請將呼叫 GoogleAuth.signOut() 方法的函式附加至連結的 onclick 事件。

<a href="#" onclick="signOut();">Sign out</a>
<script>
  function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('User signed out.');
    });
  }
</script>