在为网站集成 Google 登录时,常常会因为 OAuth 配置、Token 验证或跨域问题卡住。下面的完整指南帮你一步到位,从前端按钮到后端安全校验,全程示例代码直接可用,省去摸索时间,让用户登录体验顺畅、系统安全可靠。
前端接入(HTML / JS 简单示例)
Google 提供了非常便捷的 HTML 标签式引入或 JavaScript SDK。
方法 A:使用 HTML 快速生成登录按钮(最简单)
在网页的 <head> 或 <body> 中引入 SDK 并添加配置标签:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
| <!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Google 登录示例</title>
<!-- 1. 引入 Google Identity Services SDK -->
<script src="https://accounts.google.com/gsi/client" async defer></script>
</head>
<body>
<h2>使用 Google 账号登录</h2>
<!-- 2. 配置 Google 登录参数 -->
<div id="g_id_onload"
data-client_id="YOUR_CLIENT_ID.apps.googleusercontent.com"
data-callback="handleCredentialResponse">
</div>
<!-- 3. 渲染 Google 登录按钮 -->
<div class="g_id_signin" data-type="standard"></div>
<script>
// 4. 处理登录成功后的回调函数
function handleCredentialResponse(response) {
// response.credential 是一个 JWT Token (ID Token)
console.log("Encoded JWT ID token: " + response.credential);
// 将这个 Token 发送到你的后端服务器进行验证和登录
fetch('/api/auth/google', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: response.credential })
})
.then(res => res.json())
.then(data => {
console.log("登录成功:", data);
});
}
</script>
</body>
</html>
|
方法 B:使用 JavaScript API 方式自定义
如果需要在特定点击事件中触发或做更多自定义交互:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| window.onload = function () {
google.accounts.id.initialize({
client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
callback: handleCredentialResponse
});
google.accounts.id.renderButton(
document.getElementById("buttonDiv"),
{ theme: "outline", size: "large" } // 自定义样式
);
// 可选:弹出一键登录提示框(One Tap)
google.accounts.id.prompt();
};
|
后端验证 ID Token(极其重要)
前端获取到的 response.credential 是一个 JWT Token (ID Token)。绝对不能只在前端解密使用,必须将其发送给后端进行签名和有效性验证。
后端验证逻辑示例(Node.js 与 Python):
Node.js 示例(使用 google-auth-library)
1
| npm install google-auth-library
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| const { OAuth2Client } = require('google-auth-library');
const client = new OAuth2Client('YOUR_CLIENT_ID.apps.googleusercontent.com');
async function verify(token) {
const ticket = await client.verifyIdToken({
idToken: token,
audience: 'YOUR_CLIENT_ID.apps.googleusercontent.com', // 校验 Client ID
});
const payload = ticket.getPayload();
// 获取到的用户信息
const userid = payload['sub']; // Google 用户唯一 ID
const email = payload['email']; // 用户邮箱
const name = payload['name']; // 用户昵称
const picture = payload['picture']; // 用户头像
return { userid, email, name, picture };
}
|
Python 示例(使用 google-auth)
1
| pip install google-auth
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| from google.oauth2 import id_token
from google.auth.transport import requests
CLIENT_ID = "YOUR_CLIENT_ID.apps.googleusercontent.com"
def verify_google_token(token_string):
try:
# 验证 Token
idinfo = id_token.verify_oauth2_token(token_string, requests.Request(), CLIENT_ID)
# 获取用户信息
userid = idinfo['sub']
email = idinfo['email']
name = idinfo.get('name')
picture = idinfo.get('picture')
return { 'userid': userid, 'email': email, 'name': name, 'picture': picture }
except ValueError:
# Invalid token
return None
|
处理业务逻辑
后端成功验证 Google 传来的 ID Token 并拿到用户唯一 ID(sub)和 email 后:
- 查询数据库:检查是否已存在该
email 或 google_sub_id。 - 注册 / 绑定:
- 若不存在,自动创建新用户并记录 Google 账号信息;
- 若已存在,将当前会话与该用户关联。
- 颁发登录凭证:生成系统自己的 JWT 或 Session Cookie,返回给前端完成登录。
注意事项与常见踩坑
- 域名限制:Google OAuth 限制来源域名,测试时请确保在凭据中加入
http://localhost 或具体的本地端口。 - HTTPS 要求:生产环境中,Google 登录必须使用 HTTPS。
- 发布同意屏幕:测试阶段仅允许添加在测试列表里的 Google 账号登录。上线前,需要在 Google Cloud Console 将 OAuth 同意屏幕状态从 测试(Testing) 切换为 生产(In production)。