Google身份验证javascript

时间:2012-09-28 17:13:59

标签: javascript google-api google-api-client google-authentication

我正在尝试在我们的网站上执行google登录。我已经阅读了文档并在apis控制台上设置了一个应用程序。

我更喜欢注册对话框显示在弹出窗口中,并且在用户登录并接受我将获得javascript回调的权限之后。这个api也支持根据文档。所以我在文档的帮助下构建了以下内容; - )

第一部分是使用正确的clientid和apikey加载google客户端脚本async和init脚本。

$gp = new googlePlus('@Trustpilot.Web.Social.Google.ClientID', '@Trustpilot.Web.Social.Google.ApiKey');
(function () {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/client.js?onload=googlePlusClientLoad';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();

下一部分是使用谷歌客户端API的部分。加载client.js时调用handleClientLoad()。该方法检查使用是否经过身份验证。如果用户是,我的想法是我想登录用户。 如果用户尚未经过身份验证,则会有一个按钮,当单击handleAuthClick()时,它会调用handleClientLoad(),但会有一个弹出窗口,用户登录最多(使用谷歌帐户)并接受权限。登录后调用handleAuthResult()来登录用户。

function googlePlus(clientId, apiKey) {
    this.clientId = clientId;
    this.apiKey = apiKey;
    this.scopes = 'https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email';

    /// This method is called when the javascript is loaded async
    this.handleClientLoad = function() {
        gapi.client.setApiKey(this.apiKey);
        window.setTimeout(this.authorize(true), 1);
    };

this.handleAuthResult = function (authResult) {
    console.log(authResult);
    if (authResult && !authResult.error) {
        var token = gapi.auth.getToken();
        console.log(token);
    }
    else if (authResult && authResult.error) {
        alert(authResult.error);
    }
};

this.handleAuthClick = function(event) {
    this.authorize(false);
    return false;
};

this.makeApiCall = function() {
    gapi.client.load('plus', 'v1', function () {
        var request = gapi.client.plus.people.get({
            'userId': 'me'
        });
        request.execute(function (resp) {
            console.log(resp);
        });
    });
};

    this.authorize = function (immediate) {
        gapi.auth.authorize({ client_id: this.clientId, scope: this.scopes, immediate: immediate }, this.handleAuthResult());
        //gapi.auth.authorize({ client_id: this.clientId, scope: this.scopes, immediate: immediate }, this.handleAuthResult());
    };
}
var googlePlusClientLoad = function() {
    $gp.handleClientLoad();
};

现在解决问题:

  1. 当调用handleClientLoad时,用户永远不会被验证 如果用户已经进行了认证。
  2. 如果用户使用handleAuthClick(),则弹出窗口显示并登录,权限和 回调handleAuthResult()工作。但参数authResult是 永远不会(应该是文档中的东西)。
  3. 如果我多次尝试而不重新加载页面,我有时会这样做 获取makeApiCall()和gapi.auth.getToken()以获取我需要的信息。

1 个答案:

答案 0 :(得分:1)

您的代码中存在两个问题:

  • 不需要API密钥,您可以将其删除。您可以通过OAuth2获取用户令牌,这就足够了。
  • authorize()中,未正确调用handleAuthResult方法,请删除函数名末尾的括号。您不想执行该函数,只需传递其引用即可。以下是authorize方法的含义:

    gapi.auth.authorize({ client_id: this.clientId, scope: this.scopes, immediate: immediate }, this.handleAuthResult);

请注意括号中的差异。