Google 登錄管理 OAuth 2.0 流程和令牌生命週期,簡化您與 Google API 的集成。用戶始終可以隨時撤銷對應用程序的訪問權限。
本文檔介紹瞭如何完成基本的 Google 登錄集成。
創建授權憑證
任何使用 OAuth 2.0 訪問 Google API 的應用程序都必須具有向 Google 的 OAuth 2.0 服務器識別應用程序的授權憑據。以下步驟說明瞭如何為您的項目創建憑據。然後,您的應用程序可以使用憑據訪問您為該項目啟用的 API。
- Go to the Credentials page.
- 單擊創建憑據 > OAuth 客戶端 ID 。
- 選擇Web 應用程序類型。
- 命名您的 OAuth 2.0 客戶端並單擊創建
配置完成後,記下創建的客戶端 ID。您將需要客戶端 ID 來完成後續步驟。 (還創建了一個客戶端密碼,但您只需要它用於服務器端操作。)
加載 Google 平台庫
您必須在集成了 Google 登錄的網頁上包含 Google 平台庫。
<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、姓名、個人資料 URL 和電子郵件地址。
要檢索用戶的配置文件信息,請使用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>