Jac*_*001 0 login oauth-2.0 google-oauth
我正在尝试在我的网站中构建一个 Google 登录按钮。我试图避免使用他们的内置按钮。下面的代码可以让用户登录,但我不知道如何让我的网页在用户刷新页面或离开网站并返回时记住他们已登录。
使用 Chrome 的开发人员工具,我可以看到https://accounts.google.com在Local Storage和下都有一个条目Session Storage。它们似乎或多或少包含相同的信息,包括用户的验证令牌。
我不明白的是如何让gapi.auth2.init()函数识别和使用这个令牌。该文件似乎并没有掩盖它。
<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>
Run Code Online (Sandbox Code Playgroud)
您可以使用侦听器。这是相关部分:
// Listen for sign-in state changes.
auth2.isSignedIn.listen(signinChanged);
// Listen for changes to current user.
auth2.currentUser.listen(userChanged);
Run Code Online (Sandbox Code Playgroud)
您还可以通过以下方式获取最新值
var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
Run Code Online (Sandbox Code Playgroud)
要严格检测回访用户,您可以执行以下操作:
var auth2 = gapi.auth2.init(CONFIG);
auth2.then(function() {
// at this point initial authentication is done.
var currentUser = auth2.currentUser.get();
});
Run Code Online (Sandbox Code Playgroud)
当涉及到您的代码时,我会这样做:
auth2 = gapi.auth2.init(CONFIG);
auth2.currentUser.listen(onUserChange);
auth2.attachClickHandler(element, {});
Run Code Online (Sandbox Code Playgroud)
这样,登录状态的所有更改都会传递给 onUserChange(这包括返回用户、来自 attachClickHandler 的新登录、来自不同选项卡的新登录)。
| 归档时间: |
|
| 查看次数: |
3074 次 |
| 最近记录: |