如何使用“Google登录”(OAuth 2.0)检查用户是否已登录

23

我第一次根据这里这里的说明,使用HTML和Javascript实现Google登录。

需要解决的问题是:在不同的页面(例如登录后看到的着陆页或门户),如何检查用户是否已登录?是否有可以调用的服务来检查用户的应用密钥或类似的登录状态? 我认为我需要在每个页面上包含Google API。

登录页面代码:

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>

我是否可以在另一个页面中包含Google API,然后调用某个检查登录状态的函数?或者有其他方法可以明确地判断用户是已登录还是未登录?

5个回答

27

您不需要将任何内容存储在本地存储中。该库允许您使用 auth2gapi 对象上的 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
    }
};

别忘了更改应用程序 ID


12
你可以将自定义的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 session_start 函数才能在 JavaScript 中访问此变量? - jordan
当然可以。它可用Javascript编写,您无需引用任何第三方库。您可以从W3Schools网站上获取更多信息:http://www.w3schools.com/html/html5_webstorage.asp - Ozan Gunceler

5

要检查用户是否已登录,请使用:

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

1
这个的 oath 端点等价物是什么? - DFSFOT

3
根据Phyrik发布的链接(https://developers.google.com/identity/sign-in/web/people)- 谷歌停止支持 Sign-In Javascript 网页认证API:
引用:
我们将停止为网页提供 Google Sign-In JavaScript 平台库。该库将在2023年3月31日停用后不再提供下载。取而代之,请使用新的Google Identity Services for Web。 默认情况下,新创建的客户端ID现在被阻止使用旧的平台库,现有的客户端ID不受影响。在2022年7月29日之前创建的新客户端ID可以设置plugin_name以启用对Google平台库的使用。

1

在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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接