如何检查用户是不是使用“谷歌登录”(OAuth 2.0)登录

Posted

技术标签:

【中文标题】如何检查用户是不是使用“谷歌登录”(OAuth 2.0)登录【英文标题】:How to check if user is logged in or not with "Google Sign In" (OAuth 2.0)如何检查用户是否使用“谷歌登录”(OAuth 2.0)登录 【发布时间】:2016-10-31 05:10:05 【问题描述】:

我第一次按照here 和here 的描述实现Google 登录。

我正在使用带有 javascripthtml

需要解决的问题如下:在初次登录后,如何在不同的页面(例如登录页面,或用户登录后看到的门户)上检查用户是否已登录?我可以调用一项服务来使用我的应用程序密钥或类似的东西检查用户的登录状态吗? 我假设我必须在每个页面上包含 google API。

登录页面代码:

Script In Head(上面列出的 Google 教程中的代码):

<head>
....
<script src="https://apis.google.com/js/platform.js" async defer></script>

<script>
function onSignIn(googleUser) 

  var profile = googleUser.getBasicProfile();
  console.log('ID: ' + profile.getId()); 
  console.log('Name: ' + profile.getName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail());

  alert(profile.getName());   


function logout()

    alert('logging out');
    var auth2 = gapi.auth2.getAuthInstance();
        auth2.signOut().then(function () 
        console.log('User signed out.');
        );

...
</head> 

正文中的代码(上面列出的 Google 教程的第一行,第二行触发注销测试)

<body>
...
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<div onmousedown="logout()">Logout</div>
...
</body>

有什么方法可以在另一个页面上包含谷歌 API,然后调用一些检查登录状态函数?或者另一种具体判断用户是否登录或退出的方法?

【问题讨论】:

【参考方案1】:

您不需要在本地存储上存储任何内容。该库允许您使用gapi 对象的auth2 上的isSignedIn.get() 检查用户是否已登录。

加载 JavaScript 库,确保没有延迟加载:

<script src="https://apis.google.com/js/platform.js"></script>

然后初始化库并检查用户是否登录

var auth2;
var googleUser; // The current user

gapi.load('auth2', function()
    auth2 = gapi.auth2.init(
        client_id: 'your-app-id.apps.googleusercontent.com'
    );
    auth2.attachClickHandler('signin-button', , onSuccess, onFailure);

    auth2.isSignedIn.listen(signinChanged);
    auth2.currentUser.listen(userChanged); // This is what you use to listen for user changes
);  

var signinChanged = function (val) 
    console.log('Signin state changed to ', val);
;

var onSuccess = function(user) 
    console.log('Signed in as ' + user.getBasicProfile().getName());
    // Redirect somewhere
;

var onFailure = function(error) 
    console.log(error);
;

function signOut() 
    auth2.signOut().then(function () 
        console.log('User signed out.');
    );
        

var userChanged = function (user) 
    if(user.getId())
      // Do something here
    
;

别忘了更改app id

【讨论】:

【参考方案2】:

您可以对自定义 userEntity 对象进行字符串化并将其存储在 sessionStorage 中,您可以在加载新页面时随时检查它。我尚未测试以下内容,但它应该可以工作(以相同的方式对 WebAPI 令牌执行类似操作)

function onSignIn(googleUser) 

  var profile = googleUser.getBasicProfile();
  console.log('ID: ' + profile.getId()); 
  console.log('Name: ' + profile.getName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail());
  
  var myUserEntity = ;
  myUserEntity.Id = profile.getId();
  myUserEntity.Name = profile.getName();
  
  //Store the entity object in sessionStorage where it will be accessible from all pages of your site.
  sessionStorage.setItem('myUserEntity',JSON.stringify(myUserEntity));

  alert(profile.getName());   


function checkIfLoggedIn()

  if(sessionStorage.getItem('myUserEntity') == null)
    //Redirect to login page, no user entity available in sessionStorage
    window.location.href='Login.html';
   else 
    //User already logged in
    var userEntity = ;
    userEntity = JSON.parse(sessionStorage.getItem('myUserEntity'));
    ...
    DoWhatever();
  


function logout()

  //Don't forget to clear sessionStorage when user logs out
  sessionStorage.clear();

当然,如果 sessionStorage 对象被篡改,您可以进行一些内部检查。这种方法应该适用于 Chrome 和 Firefox 等现代浏览器。

【讨论】:

感谢您的回答 - 我会尽快尝试并更新。你能告诉我'sessionStorage'变量是javascript中的某种全局对象吗?还是您必须设置的东西?每个新页面是否仍需要调用 php sessionstart 函数才能在 javascript 中访问此变量? 当然...它在 javascript 中可用,您不需要引用任何第三方库。您可以通过w3schools.com/html/html5_webstorage.asp 从 W3Schools 获得更多信息【参考方案3】:

检查用户是否已登录使用:

gapi.auth2.getAuthInstance().isSignedIn.get()

【讨论】:

与此等效的 oath 端点是什么?【参考方案4】:

除了上面 Joseph 的回答之外,您还可以通过调用 auth2.currentUser.get().getBasicProfile() 获取有关用户的信息。

    if (auth2.isSignedIn.get()) 
        googleUserProfile = auth2.currentUser.get().getBasicProfile()
        console.log('ID: ' + googleUserProfile.getId());
        console.log('Full Name: ' + googleUserProfile.getName());
        console.log('Given Name: ' + googleUserProfile.getGivenName());
        console.log('Family Name: ' + googleUserProfile.getFamilyName());
        console.log('Image URL: ' + googleUserProfile.getImageUrl());
        console.log('Email: ' + googleUserProfile.getEmail());
    

来自文档:https://developers.google.com/identity/sign-in/web/people

【讨论】:

以上是关于如何检查用户是不是使用“谷歌登录”(OAuth 2.0)登录的主要内容,如果未能解决你的问题,请参考以下文章

如何保存使用 OAuth 2 (Spring) 登录的用户?

谷歌 Oauth 2.0 注销

如何获取谷歌登录swift 4的OAuth2授权码

我在 ios 应用程序中实现了谷歌登录。现在,我如何验证用户是不是已登录,如果没有 - 使用 Swift 将他返回到登录页面?

如何检测用户是不是第一次在 Firebase [重复]

谷歌 OAuth2 API。检查用户是不是有两因素身份验证(不是 GSuite)