Google登录状态 [英] Google SignIn State
问题描述
我正在尝试在我的网站中构建一个Google登录按钮.我试图避免使用其内置按钮.下面的代码可用于登录用户,但我无法弄清楚如何使我的网页记住用户刷新页面或离开站点并返回时它们已登录.
I'm trying to build a Google signin button into my website. I'm trying to avoid using their built-in button. The code below works to sign in a user, but I can't figure out how to make my webpage remember that they're signed in when the user refreshes the page, or leaves the site and comes back.
使用Chrome的开发人员工具,我可以看到Local Storage
和Session Storage
下都有一个https://accounts.google.com
条目.它们似乎或多或少包含相同的信息,包括用户的经过验证的令牌.
Using Chrome's developer tools, I can see that there's an entry for https://accounts.google.com
under both Local Storage
and Session Storage
. They seem to more or less contain the same information, including the user's validated token.
我不了解的是如何获取gapi.auth2.init()
函数来识别和使用此令牌. 文档似乎没有涵盖
What I don't understand is how to get the gapi.auth2.init()
function to recognize and use this token. The documentation doesn't seem to cover it.
<html>
<head>
<title>Login Test</title>
<script src="http://code.jquery.com/jquery-2.1.4.js"></script>
<script src="https://apis.google.com/js/platform.js?onload=renderButton" async defer></script>
</head>
<script>
var googleUser = {};
function renderButton() {
gapi.load('auth2', function(){
auth2 = gapi.auth2.init({
client_id: 'MY_CREDENTIALS.apps.googleusercontent.com',
});
attachSignin(document.getElementById('customBtn'));
});
};
function attachSignin(element) {
auth2.attachClickHandler(element, {},
function(googleUser) {
document.getElementById('name').innerText = "Signed in: " +
googleUser.getBasicProfile().getName();
}, function(error) {
alert(JSON.stringify(error, undefined, 2));
}
);
}
</script>
<body>
<div id="gSignInWrapper">
<span class="label">Sign in with:</span>
<input type="button" id="customBtn" value="Google"></input>
</div>
<p id="name"></p>
</body>
</html>
推荐答案
您可以使用听众.这是相关的部分:
You can use listeners. This is the relevant part:
// Listen for sign-in state changes.
auth2.isSignedIn.listen(signinChanged);
// Listen for changes to current user.
auth2.currentUser.listen(userChanged);
您还可以通过
var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
要严格只检测回头用户,您可以执行以下操作:
To strictly detect returning users only you can do:
var auth2 = gapi.auth2.init(CONFIG);
auth2.then(function() {
// at this point initial authentication is done.
var currentUser = auth2.currentUser.get();
});
当涉及到您的代码时,我会这样做:
When it comes to your code I would do:
auth2 = gapi.auth2.init(CONFIG);
auth2.currentUser.listen(onUserChange);
auth2.attachClickHandler(element, {});
通过这种方式,所有登录状态的更改都传递给onUserChange(包括返回用户,attachClickHandler的新登录,其他选项卡的新登录).
This way all changes in sign-in state are passed to onUserChange (this includes returning users, new sign-ins from attachClickHandler, new sign-ins from different tab).
这篇关于Google登录状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!