invalid_grant,通过 google api 登录后刷新网页时出现错误请求

时间:2021-04-08 12:12:06

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

我已经成功集成了 google api 登录和注销,两者都工作正常,但在我登录并尝试刷新网页后..它显示了以下错误-

<块引用>

致命错误:未捕获的 GuzzleHttp\Exception\ClientException:客户端错误:POST https://oauth2.googleapis.com/token 导致 400 Bad Request 响应:{“错误”: "invalid_grant", "error_description": "错误请求" } in C:\xamppNew\htdocs\realestate\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:113 Stack 跟踪:#0 C:\xamppNew\htdocs\realestate\vendor\guzzlehttp\guzzle\src\Middleware.php(69): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), 对象(GuzzleHttp\Psr7\Response),NULL,数组,NULL)#1 C:\xamppNew\htdocs\realestate\vendor\guzzlehttp\promises\src\Promise.php(204): GuzzleHttp\Middleware::GuzzleHttp{closure}(Object(GuzzleHttp\Psr7\Response)) #2 C:\xamppNew\htdocs\realestate\vendor\guzzlehttp\promises\src\Promise.php(153): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), NULL) #3 C:\xamppNew\htdocs\realestate\vendor\guzzlehttp\promises\src\TaskQueue.php(48): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise{closure}() #4 C:\xamppNew\ht in C:\xamppNew\htdocs\realestate\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php 第 113 行

我的 config.php -

<?php


session_start();


require_once 'vendor/autoload.php';


$google_client = new Google_Client();

$google_client->setAccessType('offline');

$google_client->setClientId('client key');


 $google_client->setClientSecret('client secret key');


$google_client->setRedirectUri('http://localhost/realestate/index.php');


$google_client->addScope('email');

$google_client->addScope('profile');

?>

我的 index.php google api 会话代码-

<?php


include('config.php');

$login_button = '';


if(isset($_GET["code"]))
{

$token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);


if(!isset($token['error']))
{

$google_client->setAccessToken($token['access_token']);


$_SESSION['access_token'] = $token['access_token'];


$google_service = new Google_Service_Oauth2($google_client);


$data = $google_service->userinfo->get();


    if(!empty($data['given_name']))
    {
    $_SESSION['user_first_name'] = $data['given_name'];
    }

    if(!empty($data['family_name']))
    {
    $_SESSION['user_last_name'] = $data['family_name'];
    }

    if(!empty($data['email']))
    {
    $_SESSION['user_email_address'] = $data['email'];
    }

    if(!empty($data['gender']))
    {
    $_SESSION['user_gender'] = $data['gender'];
    }

    if(!empty($data['picture']))
    {
        $_SESSION['user_image'] = $data['picture'];
    }
    }
 }


if(!isset($_SESSION['access_token']))
{

$login_button = '<a href="'.$google_client->createAuthUrl().'">Login With 
Google</a>';
}

?>


//this is for testing purpose 
<?php  if($login_button == '') {echo '<h3><b>Name :</b> 
'.$_SESSION['user_first_name'].' '.$_SESSION['user_last_name'].'</h3>';
                            echo '<h3><a href="logout.php">Logout</h3> 
</div>'; }?>

//这是登录按钮-

<?php echo '<a class="btn connect-google">'.$login_button . '</a>'; ?>

我的 logout.php-

<?php

include('config.php');

$accesstoken=$_SESSION['access_token'];
//Reset OAuth access token
$google_client->revokeToken($accesstoken);

//Destroy entire session data.
session_destroy();

//redirect page to index.php
header('location:index');

?>

我不知道为什么会发生这种情况以及如何解决这个问题。顺便说一句,在我通过 google api 在我的网站上登录并刷新页面后,它应该在保持登录状态时成功刷新。但它向我显示了错误,当我点击返回时,它会再次出现谷歌登录页面。

1 个答案:

答案 0 :(得分:0)

我认为您的问题是您没有正确使用刷新令牌

oauth2callback.php

注意当返回代码时我如何将访问令牌和刷新令牌存储到会话中。

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';

// Start a session to persist credentials.
session_start();

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
    $client = buildClient();
    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
    $client = buildClient();
    $client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
    // Add access token and refresh token to seession.
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();    
    //Redirect back to main script
    $redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());    
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

Oauth2Authentication.php

然后检查这个以查看我如何测试访问令牌是否已过期,如果是,我使用刷新令牌获取新令牌。

require_once __DIR__ . '/vendor/autoload.php';
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    $client = getOauth2Client();

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }
return $client;
}

/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Scopes will need to be changed depending upon the API's being accessed.
 * Example:  array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function buildClient(){
    
    $client = new Google_Client();
    $client->setAccessType("offline");        // offline access.  Will result in a refresh token
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope([YOUR SCOPES HERE]);
    $client->setRedirectUri(getRedirectUri());  
    return $client;
}

/**
 * Builds the redirect uri.
 * Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
 * Hostname and current server path are needed to redirect to oauth2callback.php
 * @return A redirect uri.
 */
function getRedirectUri(){

    //Building Redirect URI
    $url = $_SERVER['REQUEST_URI'];                    //returns the current URL
    if(strrpos($url, '?') > 0)
        $url = substr($url, 0, strrpos($url, '?') );  // Removing any parameters.
    $folder = substr($url, 0, strrpos($url, '/') );   // Removeing current file.
    return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}


/**
 * Authenticating to Google using Oauth2
 * Documentation:  https://developers.google.com/identity/protocols/OAuth2
 * Returns a Google client with refresh token and access tokens set. 
 *  If not authencated then we will redirect to request authencation.
 * @return A google client object.
 */
function getOauth2Client() {
    try {
        
        $client = buildClient();
        
        // Set the refresh token on the client. 
        if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
            $client->refreshToken($_SESSION['refresh_token']);
        }
        
        // If the user has already authorized this app then get an access token
        // else redirect to ask the user to authorize access to Google Analytics.
        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
            
            // Set the access token on the client.
            $client->setAccessToken($_SESSION['access_token']);                 
            
            // Refresh the access token if it's expired.
            if ($client->isAccessTokenExpired()) {              
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                $client->setAccessToken($client->getAccessToken()); 
                $_SESSION['access_token'] = $client->getAccessToken();              
            }           
            return $client; 
        } else {
            // We do not have access request access.
            header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
        }
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

用户信息

此外,您还应该考虑通过 People api 而不是 userinfo 端点,它在请求用户个人资料信息时更加稳定,因为您已经在请求电子邮件和个人资料范围,您应该已经拥有访问权限。