简体   繁体   English

使用Google登录检查登录的Google用户

[英]Checking for signed in Google user with Google Sign-in

I'm working with the Google Sign-in library. 我正在使用Google登录库。

If I use Google's provided sign in button on my page, it quickly changes states to show that I am logged in before I've taken any action. 如果我使用页面上Google 提供的登录按钮 ,它会快速更改状态以显示我已登录,然后再执行任何操作。

Is it possible to detect this signed in state without using Google's default button? 是否可以在不使用Google默认按钮的情况下检测到此登录状态?

The main issue is that their button doesn't allow for checking for the hosted domain of the logged in account. 主要问题是其按钮不允许检查已登录帐户的托管域。

I was trying to use the GoogleAuth.currentUser.get() function to get the user, but as the documentation notes: 我试图使用GoogleAuth.currentUser.get()函数来获取用户,但如文档所述

in a newly-initialized GoogleAuth instance, the current user has not been set. 在新初始化的GoogleAuth实例中,当前用户尚未设置。 Use the currentUser.listen() method or the GoogleAuth.then() to get an initialized GoogleAuth instance. 使用currentUser.listen()方法或GoogleAuth.then()获取初始化的GoogleAuth实例。

Using GoogleAuth.then(onInit, onFailure) as mentioned above correctly retrieves the logged in state of the user. GoogleAuth.then(onInit, onFailure)使用GoogleAuth.then(onInit, onFailure)可以正确检索用户的登录状态。

/**
 * The Sign-In client object.
 */
var auth2;

/**
 * Initializes the Sign-In client.
 */
var initClient = function() {
  gapi.load('auth2', function(){
    /**
     * Retrieve the singleton for the GoogleAuth library and set up the
     * client.
     */
    auth2 = gapi.auth2.init({
        client_id: CLIENT_ID,
        scope: 'profile'
    });

    // Called once auth2 has finished initializing
    auth2.then(checkForLoggedInUser, onFailure);

  });
};

function checkForLoggedInUser() {
  var user = auth2.currentUser.get();
  var profile = user.getBasicProfile();
  console.log('Email: ' + profile.getEmail());
}

You can use the GoogleAuth.isSignedIn.get() method: 您可以使用GoogleAuth.isSignedIn.get()方法:

// 1. Make gapi.auth2 available (using gapi.load("auth2", ...))
// 2. Initialize the library (using gapi.init({ ... }))
const isSignedIn = gapi.auth2.getAuthInstance().isSignedIn.get();

isSignedIn is true if the user is signed to Google, otherwise false . 如果用户已登录Google,则isSignedIntrue ,否则为false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM