Google 登入會管理 OAuth 2.0 流程和權杖生命週期,以及簡化與 Google API 的整合作業。使用者隨時可以撤銷應用程式的存取權。
本文件將說明如何實作基本的 Google 登入。
建立授權憑證
凡是使用 OAuth 2.0 存取 Google API 的應用程式,都必須具備可讓 Google 的 OAuth 2.0 伺服器識別應用程式的授權憑證。下列步驟說明如何為專案建立憑證。然後,您的應用程式就能使用憑證存取您為該專案啟用的 API。
- Go to the Credentials page.
- 按一下 [Create credentials] (建立憑證) > [OAuth client ID] (OAuth 用戶端 ID)。
- 選取「Web application」(網頁應用程式) 應用程式類型。
- 為 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-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>