將 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 用戶端命名,然後按一下「建立」

設定完成後,請記下已建立的用戶端 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-signin2 類別的 div 元素:

<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>