Google_Auth_Exception'有消息'错误提取OAuth2访问令牌,消息:' invalid_grant'

时间:2014-10-01 11:40:11

标签: javascript php google-plus google-oauth google-api-php-client

我正在尝试按照Google Developer's website中的说明略微改变Google+网络登录服务器端流程。

我有一个员工登录页面(staff_login.php),它使用javascript通过Google+(plusone.js)。 如果用户已登录Google,则Google的授权代码会存储到会话变量中。 如果用户未登录,则会显示“员工登录”按钮。如果用户点击该按钮,则会发生Google授权,如果成功,则Google的授权代码会存储到会话变量中。 在这两种情况下,在存储会话变量之后,用户将被重定向到另一个网页(google_login.php)。

大多数情况下,登录过程按预期工作,但有时google_login.php会生成错误消息:Google_Auth_Exception',并显示消息'获取OAuth2访问令牌时出错,消息:'invalid_grant'。

我很确定问题出在signInCallback函数中。如何使其防弹?

这是(缩减)代码:

staff_login.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="google-signin-clientid"
          content="CLIENT-ID.apps.googleusercontent.com">
    <meta name="google-signin-scope" content="email">
    <meta name="google-signin-cookiepolicy" content="single_host_origin">
    <meta name="google-signin-callback" content="signInCallback">
    <title>Login</title>
</head>
<body>

<button id="xyzStaffSignIn">Staff Sign In</button>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" 
    type="text/javascript"></script>

<script type = "text/javascript" >

    jQuery(document).ready(function ($) {
        console.log('Google (plusone.js) will invoke signInCallback');

        window.___gcfg = {
            lang: 'en-GB',
            parsetags: 'onload'
        };
        var po = document.createElement('script');
        po.type = 'text/javascript';
        po.async = true;
        po.src = 'https://apis.google.com/js/client:plusone.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(po, s);
    });

    function signInCallback(authResult) {
        if (authResult) {
            if (authResult['error'] == undefined) {
                if (authResult['code']) {
                    setSessionValue('GoogleAuthorisationCode', 
                       authResult['code'], callGoogleLogin);
                }
            } else if (authResult['error']) {
                // There was an error.
                // Possible error codes:
                //   "access_denied" - User denied access to your app
                //   "immediate_failed" - Could not automatically log in the user
                console.log('There was an error: ' + authResult['error']);

                if (!authResult['status']['signed_in']) {
                    console.log('gapi.signin.render will invoke signInCallback');
                    gapi.signin.render('xyzStaffSignIn');
                }
            } else {
                console.log('Empty authResult');  // Something went wrong
            }

        }
    }

    function setSessionValue(key, value, callback) {
        $.post(
            'session.php',
            {
                xyzAction: 'set',
                xyzKey: key,
                xyzValue: value
            },
            function (result) {
                // Handle or verify the server response if necessary.

                if (result['status'] == undefined) {
                    alert('xyz status problem. Please email our IT department!');
                } else {
                    switch (result['status']) {
                        case 'Success':
                            callback();
                            break;
                        default:
                            alert('xyz unexpected status problem. 
                                Please email our IT department!');
                            console.log(result['status']);
                    }
                }
            }
        )
    }

    function callGoogleLogin() {
        gapi.client.load('plus', 'v1', loadProfile);
    }

    /**
     * Uses the JavaScript API to request the user's profile, which includes
     * their basic information. When the plus.profile.emails.read scope is
     * requested, the response will also include the user's primary email address
     * and any other email addresses that the user made public.
     */
    function loadProfile() {
        var request = gapi.client.plus.people.get({'userId': 'me'});
        request.execute(loadProfileCallback);
    }

    /**
     * Callback for the asynchronous request to the people.get method. The profile
     * and email are set to global variables. Triggers the user's basic profile
     * to display when called.
     */

    function loadProfileCallback(profile) {
        var emailAddress;

        // Filter the emails object to find the user's primary account, which might
        // not always be the first in the array. The filter() method supports IE9+.
        emailAddress = profile['emails'].filter(function (v) {
            return v.type === 'account'; // Filter out the primary email
        })[0].value; // get the email from the filtered results, should always be defined.
        var domain = emailAddress.replace(/.*@/, "");
        if ("xyz.com" == domain) {
            window.location.href = "google_login.php?xyzEmailAddress=" + emailAddress;
        } else {
            alert(emailAddress + ' is not a recognized xyz staff member email address.');
        }
    }
</script>
</body>
</html>

google_login.php

<?php
// This code is called from the javascript on the login screen only 
// AFTER Google authorization has succeeded

// Google_Client is as defined at
// https://github.com/google/google-api-php-client/blob/master/src/Google/Client.php

$googleClient = new Google_Client ();
$googleClient->setRedirectUri('postmessage');
$googleClient->authenticate($_SESSION['GoogleAuthorizationCode']);

1 个答案:

答案 0 :(得分:1)

需要在左侧面板https://console.developers.google.com添加/启用API。 我添加的API是&#34; google + API&#34;和&#34; gmail API&#34;。我试过,它对我有用。