將 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. 選取「網頁應用程式」應用程式類型。
  4. 為 OAuth 2.0 用戶端命名,然後按一下「建立」

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

載入 Google Platform Library

您必須在已整合的網頁中加入 Google Platform Library Google 登入。

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

指定應用程式的用戶端 ID

指定您在 Google Developers Console 中為應用程式建立的用戶端 ID 與 google-signin-client_id 中繼標記元素搭配使用

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

新增 Google 登入按鈕

如要在網站中新增 Google 登入按鈕,最簡單的方法就是使用 自動轉譯的登入按鈕。只需加入幾行程式碼 加入可自動設定適當的文字的按鈕 使用者登入狀態的標誌和顏色,以及您要求的範圍。

如要建立採用預設設定的 Google 登入按鈕,請新增 div 將含有 g-signin2 類別的元素新增至登入頁面:

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