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

jor*_*dan 11 html javascript oauth google-api oauth-2.0

我正在首次实施Google登录,如此此处所述.

我正在使用HTML和Javascript.

需要解决的问题如下:在初次登录后,如何在不同的页面(例如登录页面或登录后用户看到的门户网站)上检查用户是否已登录?是否有我可以通过我的应用密钥或类似方式调用用户登录状态的服务?我想我必须在每个页面上包含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> 
Run Code Online (Sandbox Code Playgroud)

Code In Body(上面列出的Google教程的第一行,触发注销测试的第二行)

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

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

Jos*_*eph 8

您无需在本地存储中存储任何内容。图书馆可以让你检查,如果用户登录或不使用isSignedIn.get()auth2的的gapi对象。

加载JavaScript库,确保不延迟加载:

<script src="https://apis.google.com/js/platform.js"></script>
Run Code Online (Sandbox Code Playgroud)

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

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
    }
};
Run Code Online (Sandbox Code Playgroud)

别忘了更改 app id


Oza*_*ler 6

您可以对自定义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();
}
Run Code Online (Sandbox Code Playgroud)

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


Igo*_*vic 5

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

gapi.auth2.getAuthInstance().isSignedIn.get()
Run Code Online (Sandbox Code Playgroud)