这与关于google plus:防止使用Google +自动登录的问题有关。
不同之处在于,我使用的是google登录平台,而不是google,后者有不同的api。
背景:
我有一个价格页面,有一个免费试用注册表格。表单中有google登录按钮。我希望一个签名的用户仍然能够看到定价页面,而没有谷歌的标志-在导致重定向。
我的代码
我的页面顶部有一个元标记来标识我的应用程序。<meta name="google-signin-client_id" content="MY_CLIENT_ID">
我在我的页面上包含了这个脚本:<script src="https://apis.google.com/js/platform.js"></script>
我有一个呈现按钮的div:<div class="g-signin2" data-onsuccess="onSignIn"></div>
我的onSignIn函数如下所示:
function onSignIn(googleUser) {
var id_token = googleUser.getAuthResponse().id_token;
$('#google_token').val(id_token); //hidden form value
$('#google-oauth').submit(); //hidden form
}隐藏表单被提交到后端,其中令牌用于检索用户的电子邮件地址和名称,然后创建一个用户帐户并将其登录。
我的问题是,如果用户已经登录,谷歌将自动调用onSignIn函数,从而在页面加载时提交表单。有什么方法可以防止自动调用onSignIn函数吗?
参考资料:https://developers.google.com/identity/sign-in/web/sign-in
发布于 2018-04-27 18:24:11
下面是我的方法:-当页面加载时,如果用户被google标记,我们就_counter + 1,因此,如果_counter != 1,我们可以做任何事情,因为_counter==1是页面负载,如果标记的话
<script>
var GoogleOAuth = {
_counter: 0,
_gauth: null,
init:function() {
gapi.auth2.init({
client_id:'xxxxidclientxxx.apps.googleusercontent.com',
scope: 'email profile openid'
}).then(function() {
GoogleOAuth._gauth = gapi.auth2.getAuthInstance();
var isSigned = GoogleOAuth._gauth.isSignedIn.get();
if (isSigned) {
GoogleOAuth._counter++;
}
gapi.signin2.render('btnGooglelogin', {
'scope': 'profile email',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': GoogleOAuth.onSignIn,
'onfailure': GoogleOAuth.onFail
});
});
},
onSignIn: function (googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var name = profile.getName();
var avatarUrl = profile.getImageUrl();
var email = profile.getEmail();
var idToken = googleUser.getAuthResponse().id_token;
if (email == '' || idToken == '') {
alert('Your email will become username, please public your email');
return;
}
if (GoogleOAuth._counter == 1) {
GoogleOAuth._counter++;
return;
}
$.post('/User/Googlelogin', { idToken: idToken, googleId:id,name:name,avatarUrl:avatarUrl,email:email})
.done(function(data) {
if (data.Ok) {
window.location='/';
} else {
alert(data.Message);
}
}).fail(function() {
alert("Error. can not process");
});
},
signOut: function () {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut();
},
onFail:function(error){}
}
</script>
<script src="https://apis.google.com/js/platform.js?onload=googleOnload" async defer></script>
<script>
function googleOnload() {
gapi.load('auth2', function () {
GoogleOAuth.init();
});
}
</script>https://stackoverflow.com/questions/40983266
复制相似问题