我正在尝试学习如何为我的网站使用 Google 登录。我正在按照我在此页面上找到的指南进行操作:https://developers.google.com/identity/sign-in/web/
所以我创建了一个新文档,并复制/粘贴了他们在上一页中建议的代码。我在标签中添加了我的客户端 ID,并测试了代码。 一切正常,我可以登录。登录按钮更改为已登录而不是登录。此外,在我查看我的控制台时,我可以看到来自 console.log() 的数据,例如 ID、电子邮件、姓名...
我继续阅读指南,找到了如何在此页面上添加退出按钮:https://developers.google.com/identity/sign-in/web/sign-in 我实现了这段代码,这是我拥有的完整代码(没有客户端 ID)
<html lang="en">
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<a href="#" onclick="signOut();">Sign out</a>
<script>
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server!
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
};
</script>
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
</script>
</body>
</html>
当我点击它时,我会看到“用户已退出”。在我的控制台中。但是,如果我刷新页面,谷歌按钮仍然显示我已登录,并且个人资料信息会返回到我的控制台中 - 即使我手动清除控制台也是如此。注销按钮显然不起作用,我不知道为什么。
谁有这方面的经验?
感谢您的帮助!
最佳答案
为了调用 signOut
,您需要调用 authorize()
来获取用于将用户标记为已退出的 id_token。
参见 this issue在 google-api-javascript-client GitHub 上。
那里发布了一个代码示例,说明您需要先调用 gapi.auth.authorize
,并使用调用 gapi.auth.signOut()
的回调函数。
本质上是这样的:
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES,
'immediate': false,
cookie_policy: 'single_host_origin',
response_type: 'token id_token'
},
function (authResult) { gapi.auth.signOut();}
);
关于javascript - 无法使用 google-signin 注销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45203124/