google文档: 概览 | Authentication | Google for Developers
1, 前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Google Login Example</title>
<script src="https://accounts.google.com/gsi/client" async defer></script>
<style>
#google-login {
position: absolute;
top: 60%;
left: 50%;
transform: translate(-50%, 0%);
z-index: 9999;
}
</style>
</head>
<body>
<!--此代码可以在google说明文档'生成集成代码'中生成-->
<div id="g_id_onload"
data-client_id="xxxxxxx-xxxxxx.apps.googleusercontent.com"
data-context="signin"
data-ux_mode="popup"
data-callback="handleCredentialResponse"
data-auto_prompt="false">
</div>
<div id="google-login" >
<div class="g_id_signin"
data-type="standard"
data-shape="rectangular"
data-theme="outline"
data-text="signin_with"
data-size="medium"
data-logo_alignment="left">
</div>
</div>
<script>
function handleCredentialResponse(response) {
console.log( ">> 111111 handleCredentialResponse: ", response );
// 将 ID 令牌发送到服务器
let url = "https://xxxx/auth/google";
fetch( url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id_token: response.credential
})
})
.then(response => {
if (response.ok) {
return response.text();
} else {
throw new Error("Network response was not ok");
}
})
.then(async (data) => {
console.log( ">> rsp: ", data );
data = JSON.parse(data);
if (data.state == 1) {
console.log( ">> auth success" );
// ....
}
else{
}
});
}
</script>
</body>
</html>
运行测试:
开启本地http服务:python -m http.server 8000
浏览器打开: http://localhost:8000
2, 服务端验证代码:
// npm install express express-session google-auth-library
// 也可以用其它模块来创建http服务器,比如'http'
const express = require('express');
const session = require('express-session');
const { OAuth2Client } = require('google-auth-library');
const CLIENT_ID = 'YOUR_GOOGLE_CLIENT_ID';
const client = new OAuth2Client(CLIENT_ID);
const app = express();
app.use(express.json());
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true
}));
// 验证 Google ID 令牌并创建会话
app.post('/auth/google', async (req, res) => {
const { id_token } = req.body;
try {
const ticket = await client.verifyIdToken({
idToken: id_token,
audience: CLIENT_ID
});
const payload = ticket.getPayload();
req.session.user = {
name: payload.name,
email: payload.email,
picture: payload.picture
};
res.status(200).send('Login successful');
} catch (error) {
res.status(401).send('Invalid token');
}
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});