当前位置: 首页 > 知识库问答 >
问题:

invalid_grant,通过谷歌api登录后刷新网页时请求错误

伯彦君
2023-03-14

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

致命错误:未捕获的GuzzleHttp\异常\客户端异常:客户端错误:POSThttps://oauth2.googleapis.com/token导致一个400坏请求响应:{"错误":"invalid_grant","error_description":"坏请求"}在C:\xamppNew\htdocs\real房地产\供应商\guzzlehttp\GuzzleHttp\src\异常\请求xception.php:113堆栈跟踪:#0 C:\xamppNew\htdocs\real房地产\供应商\guzzlehttp\guzzle\src\Middleware.php(69): GuzzleHttp\Excelie\请求异常::create(对象(GuzzleHttp\Psr7\请求),对象(GuzzleHttp\Psr7\响应),NULL,数组,NULL)#1 C:\xamppNew\htdocs\real房地产\供应商\guzzlehttp\promise\src\Promise.php(204): GuzzleHttp\Middleware::GuzzleHttp{闭包}(对象(GuzzleHttp\Psr7\响应))#2 C:\xamppNew\htdocs\real房地产\供应商\guzzlehttp\promise\src\Promise.php(153): GuzzleHttp\Promise\Promise::callHandler(1,对象(GuzzleHttp\Psr7\响应), NULL)#3 C:\xamppNew\htdocs\real\供应商\guzzlehttp\promise\src\TaskQueue.php(48): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise{闭包}()#4 C:\xamppNew\ht inC:\xamppNew\htdocs\real财产\供应商\guzzlehttp\guzzlehttp\src\Excelie\在113行上请求xception.php

My 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.phpgoogle 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');

?>

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

共有1个答案

严升
2023-03-14

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

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

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));
}

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

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();
    }
}

此外,在请求用户配置文件信息时,您应该考虑通过Apple API代替UsReFieldEndoPoT,因为您已经请求了电子邮件和配置文件范围,您应该已经有了访问权限。

 类似资料:
  • 我正试图在他过期后获得一个新的访问令牌。我已将收到的信息保存在银行中,作为第一次客户访问的回报: {"access_token":"TOKEN","refresh_token":"TOKEN","token_type","承载","expires_in": 3600,"创建": 1320790426} 令牌到期后,我需要申请一个新的令牌,我这样做: 问题是总是返回以下错误:刷新OAuth2令牌时出

  • 我试图将谷歌登录集成到我的应用程序中。我没有后端服务器,我只是得到登录到我的应用程序的谷歌帐户的详细信息。 我第一次尝试使用谷歌登录的例子,但我得到了一个错误(除了打印下面的stacktrace外,没有进行任何代码更改)。我只是使用了signianctivity示例,因为我没有后端服务器。 密码 从我所读到的,这个问题可能是由SHA1一代引起的。 我遵循了完整的指南,但显然它不起作用。 我从gra

  • 公共类GoogleContact{private static final JsonFactory JSON_FACTORY=new JacksonFactory(); }响应为:com.google.api.client.auth.oauth2.TokenResponseException:400错误请求{“错误”:“无效_grant”,“错误_description”:“错误请求”}位于com

  • 问题内容: 好的,我有一个仅包含的简单表格。当我们点击submit(通过ajax存储)时,在文本字段中写入的数据将存储在DB中。Ajax可以正常工作并提交数据,但是,页面会自动刷新,并且URL包含输入字段的内容。 我的表格: 阿贾克斯:- PHP的:- 结果显示在后,页面将刷新,URL变为: -chat.php?message = 454545&submit_message = 为什么要刷新页面?

  • 当我构建我的应用程序并尝试它时,没有任何错误,但当我在google play store上发布我的应用程序并尝试登录Facebook时,它会给我一个错误。这个错误是一个错误的散列键,因为散列键发生了变化(我得到了sign应用程序的散列键,通过许多方式给了我相同的has键,工作正常)这是第一个问题。 我的第二个问题是当尝试使用gmail登录(谷歌登录)获取字段错误。 (您有错误的OAuth2相关配置

  • 我正在使用IdentityServer3的混合流。我已经启用了offline_access范围,以便获取刷新令牌。当我的访问令牌过期时,我将调用endpoin。我将client_id、client_secret、refresh_token和grant_type(=refresh_token)作为body的一部分传递。我得到错误。