javascript - 如何使用谷歌一键登录提取用户的完整信息?
问题描述
我正在尝试为 Google 我的业务创建一个平台,并且我已经实现了一次点击登录,并且我正在获取凭据但不是完整的信息。这是我尝试过的代码
<script>
window.onload = function () {
google.accounts.id.initialize({
client_id: "clientid.apps.googleusercontent.com",
callback: handleCredentialResponse,
});
google.accounts.id.prompt((notification) => {
if (notification.isNotDisplayed() || notification.isSkippedMoment()) {
console.log("opted out");
}
});
function handleCredentialResponse(response) {
console.log(response)
// window.location = "https://github.com/";
}
};
</script>
这是我得到的回应
{
clientId:
"clientid.apps.googleusercontent.com",
credential:
"eyJhbGciOiJSUzI1NiIsImtpZCI6ImYwNTQxNWIxM2FjYjk1OT…40Jk8v3LcOvtopFD_tI2HMlFjg0dK96XrqNiOD0H3Akl",
select_by: "user",
};
解决方案
您可以使用此函数来解析 JWT 令牌:
function parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
};
然后你可以这样做:
function handleCredentialResponse(response) {
//console.log(response)
console.log(JSON.stringify(parseJwt(response.credential)));
}
结果:
推荐阅读
- c# - 无法为 Xamarin.Forms 项目命名空间创建 xmlns
- high-availability - 如果 Autosys EEM 在一侧出现故障,另一侧的 WCC 会起作用吗?
- cookies - Google 系列产品的 GDPR 合规性充分性
- python - 子列表的总和
- javascript - Facebook - 无效范围:manage_pages
- r - r - 在带有 NAs 的 df 中按等级过滤 - 不工作
- ffmpeg - ffmpeg 将三个图像组合成一个循环视频
- java - 运营链
- javascript - Mapbox 更改标记位置和颜色
- php - 使用 php 设置 cookie