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、姓名、个人资料网址和电子邮件地址。
如需检索用户的个人资料信息,请使用 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 帐号就能退出您的应用。如需创建退出链接,请向该链接的 onclick
事件附加一个调用 GoogleAuth.signOut()
方法的函数。
<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>