Cha*_*001 4 javascript google-api google-api-js-client google-cloud-platform google-signin
我正在移植一些现有的 js 代码,通过谷歌云平台进行身份验证(因为它们正在迁移到一组新的库)。
(迁移指南:https://developers.google.com/identity/oauth2/web/guides/migration-to-gis)
我正在努力获取玩家的个人资料(以获取他们的电子邮件)。
旧的方法将遵循这一点(但正如它所说,它现在已被弃用 - 我一直在阅读新文档,但它主要围绕获得授权/身份验证而不是后续内容): https:// Developers.google.com/identity/sign-in/web/people
例如
var profile = auth2.currentUser.get().getBasicProfile();
var email = profile.getEmail();
Run Code Online (Sandbox Code Playgroud)
在我的新代码中,我通过新方法获得了访问令牌:
client_id: vm.clientId,
scope: SCOPE,
callback: (tokenResponse) => {
if (tokenResponse && tokenResponse.access_token) {
access_token = tokenResponse.access_token;
// HERE??? HOW DO I GET THE PROFILE?
}
}
})
Run Code Online (Sandbox Code Playgroud)
(主要取自https://developers.google.com/identity/oauth2/web/guides/use-token-model)
我在其他地方看到过这一点,但至少在我的情况下不起作用:
gapi.client.oauth2.userinfo.get().execute(function (resp) {
console.log(resp);
})
Run Code Online (Sandbox Code Playgroud)
(如何从 Google Identity Services 获取个人资料信息?)
我已阅读迁移指南:“相反,请使用对新 JWT CredentialResponse 对象中的凭据子字段的直接引用来处理用户配置文件数据。” 但不知道如何获得此 Credentialresponse?(https://developers.google.com/identity/gsi/web/guides/migration#token_response)
您可以按照我必须执行的这些步骤来使用 实现整个流程Javascript。
首先创建一个button包含 HTML 元素的元素:
<button id="btnGoogleSignIn" style="border:none;background: none;"> </button>
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用下面的脚本和相关函数,在其中我从 Google 获取 JWT 令牌,然后对其进行解码以获取所需的信息,例如电子邮件地址等。请注意,我正在调用 onSignInGSI 作为按钮初始化的回调。
<script>
function decodeJwtResponseFromGoogleAPI(token) {
let base64Url = token.split('.')[1]
let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
let jsonPayload =
decodeURIComponent(atob(base64).split('').map(function (c) {
return '%' + ('00' +
c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload)
}
function onSignInGSI(response) {
//console.log(response)
responsePayload = decodeJwtResponseFromGoogleAPI(response.credential);
console.log("ID: " + responsePayload.sub);
console.log('Full Name: ' + responsePayload.name);
console.log('Given Name: ' + responsePayload.given_name);
console.log('Family Name: ' + responsePayload.family_name);
console.log("Image URL: " + responsePayload.picture);
console.log("Email: " + responsePayload.email);
}
window.onload = function () {
google.accounts.id.initialize({
client_id: client_id,
context: 'signin',
callback: onSignInGSI
});
google.accounts.id.prompt();
google.accounts.id.renderButton(document.getElementById("btnGoogleSignIn"),
{
type: "standard",
text: "signin_with",
logo_alignment: "left",
width: 375
});
};
</script>
<script src="https://accounts.google.com/gsi/client" async defer></script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1721 次 |
| 最近记录: |