无法刷新PHP中的OAuth2令牌,无效的授权 [英] Unable to refresh OAuth2 token in PHP, invalid grant

查看:483
本文介绍了无法刷新PHP中的OAuth2令牌,无效的授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要制作一个PHP脚本,在Google日历上创建一个单独的事件。
我在设置客户端ID,客户端密钥,开发密钥和创建新事件方面没有任何问题。



我唯一的问题是使用OAuth2,特别是我需要以建立永久连接,并且我不想每次运行脚本都进行身份验证。



实际上,通过此脚本,我可以获得令牌和刷新令牌,但每小时我的令牌过期,我不知道如何刷新它。我如何编辑这段代码来做到这一点?
我可以将令牌和刷新令牌都保存在某个地方,并且始终使用相同的数据吗?



我得到一个未捕获异常'Google_AuthException',并显示'Error refreshing OAuth2令牌,消息:'{error:invalid_grant

我已经阅读了一些关于此主题的其他帖子,这里在stackoverflow中,但我还没有找到解决方案...:\

 <?php 

require_once'src / Google_Client。 PHP的;
require_once'src / contrib / Google_CalendarService.php';
session_start();

$ client = new Google_Client();
$ client-> setApplicationName(Calendar App);
$ client-> setClientId('xxxx');
$ client-> setClientSecret('yyy');
$ client-> setRedirectUri('http://www.zzzzzz');
$ client-> setDeveloperKey('kkk');
$ client-> setAccessType('offline');
$ cal = new Google_CalendarService($ client);

if(isset($ _ GET ['logout'])){
unset($ _ SESSION ['token']);


if(isset($ _ GET ['code'])){
$ client-> authenticate($ _ GET ['code']);
$ _SESSION ['token'] = $ client-> getAccessToken();
header('Location:http://'。$ _SERVER ['HTTP_HOST']。$ _SERVER ['PHP_SELF']);
}

if(isset($ _ SESSION ['token'])){
// echo $ _SESSION ['token'];
// $ client-> setAccessToken($ _ SESSION ['token']);
$ authObj = json_decode($ _ SESSION ['token']);
$ accessToken = $ authObj-> access_token;
$ refreshToken = $ authObj-> refresh_token;
$ tokenType = $ authObj-> token_type;
$ expiresIn = $ authObj-> expires_in;
回显'access_token ='。 $的accessToken;
echo'< br />';
echo'refresh_token ='。 $ refreshToken;
echo'< br />';
echo'token_type ='。 $ tokenType;
echo'< br />';
echo'expires_in ='。 $ expiresIn;如果(!empty($ cookie)){
$ client-> refreshToken($ this-> Cookie-> read('token'))


) ;


if($ client-> getAccessToken()){
$ calList = $ cal-> calendarList-> listCalendarList();
$ _SESSION ['token'] = $ client-> getAccessToken();
} else {
$ authUrl = $ client-> createAuthUrl();
print< a class ='login'href ='$ authUrl'>连接我!< / a>;
}


//创建单个事件
$ event = new Google_Event();
$ event-> setSummary($ event_name);
$ event-> setLocation('');
....

?>

非常感谢您的支持!

解决方案

此网页 https://developers.google .com / accounts / docs / OAuth2WebServer#offline 解释了刷新令牌如何工作,以及如何使用它来使用原始http获取新的访问令牌。



从这个问题如何使用Google API客户端刷新令牌?这里是php的等价物

 这里是要设置的代码片段令牌,在此之前确保访问类型应设置为脱机

if(isset($ _ GET ['code'])){
$ client-> authenticate();
$ _SESSION ['access_token'] = $ client-> getAccessToken();
}
刷新令牌

$ google_token = json_decode($ _ SESSION ['access_token']);
$ client-> refreshToken($ google_token-> refresh_token);
这将刷新您的令牌,您必须在会话中更新它,以便您可以执行

$ _SESSION ['access_token'] = $ client-> getAccessToken()

调试
按照以下三个步骤调试任何oauth应用程序


  1. 请确保您已阅读 https://developers.google.com/accounts/docs/OAuth2 以及相应的子页面(webapp,javascript等),具体取决于您使用哪种oauth风格。如果您不明白它在做什么,那么您不会在很远的地方调试您的应用。

  2. https://developers.google.com/oauthplayground/ ,以浏览Oauth步骤并最终完成Google API调用。这将确认你的理解,并告诉你什么HTTP调用和响应看起来像 使用跟踪/日志记录/代理等来跟踪你的应用程序的实际HTTP流量。将此与您在步骤2中观察到的情况进行比较。这应该会告诉您问题出在哪里。

    I need to make a PHP script that creates a sigle event on Google Calendar. I had no problems setting up client id, client secret, dev key and creating a new event.

    My only problem is with OAuth2, in particular I need to make a permanent connection and I do not want to do the authentication everytime I run the script.

    Actually, with this script I'm able to get a token and a refresh token, but every hour my token expires and I don't know how to refresh it. How can I edit this code to do that? Can I save both the token and the refresh token somewhere and always use the same data?

    I obtain an uncaught exception 'Google_AuthException' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant"

    I have already read some other posts about this topic here in stackoverflow but I still haven't found a solution... :\

    <?php
    
     require_once 'src/Google_Client.php';
     require_once 'src/contrib/Google_CalendarService.php';
     session_start();
    
     $client = new Google_Client();
     $client->setApplicationName("Calendar App");
     $client->setClientId('xxxx');
     $client->setClientSecret('yyy');
     $client->setRedirectUri('http://www.zzzzzz');  
     $client->setDeveloperKey('kkk');
     $client->setAccessType('offline');
     $cal = new Google_CalendarService($client);    
    
    if (isset($_GET['logout'])) {
      unset($_SESSION['token']);
    }
    
    if (isset($_GET['code'])) {
      $client->authenticate($_GET['code']);
      $_SESSION['token'] = $client->getAccessToken();
      header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); 
    }
    
    if (isset($_SESSION['token'])) {
        //echo $_SESSION['token'];
      //$client->setAccessToken($_SESSION['token']);
        $authObj = json_decode($_SESSION['token']);
        $accessToken = $authObj->access_token;
        $refreshToken = $authObj->refresh_token;
        $tokenType = $authObj->token_type;
        $expiresIn = $authObj->expires_in;
        echo 'access_token = ' . $accessToken;
        echo '<br />';
        echo 'refresh_token = ' . $refreshToken;
        echo '<br />';
        echo 'token_type = ' . $tokenType;
        echo '<br />';
        echo 'expires_in = ' . $expiresIn;
    }
    
    if(!empty($cookie)){
        $client->refreshToken($this->Cookie->read('token'));
    }
    
    if ($client->getAccessToken()) {
        $calList = $cal->calendarList->listCalendarList();
        $_SESSION['token'] = $client->getAccessToken();
    } else {
      $authUrl = $client->createAuthUrl();
      print "<a class='login' href='$authUrl'>Connect Me!</a>";
    }
    
    
    // Creation of a single event
    $event = new Google_Event();
    $event->setSummary($event_name);            
    $event->setLocation('');                    
    ....
    
    ?>
    

    Thanks a lot for your support!

    解决方案

    This page https://developers.google.com/accounts/docs/OAuth2WebServer#offline explains how the refresh token works, and how to use it to get a fresh access token using raw http.

    From this question How to refresh token with Google API client? here is the php equivalent

    here is the snippet to set token, before that make sure the access type should be set to offline
    
    if (isset($_GET['code'])) {
      $client->authenticate();
      $_SESSION['access_token'] = $client->getAccessToken();
    }
    To refresh token
    
    $google_token= json_decode($_SESSION['access_token']);
    $client->refreshToken($google_token->refresh_token);
    this will refresh your token, you have to update it in session for that you can do
    
     $_SESSION['access_token']= $client->getAccessToken()
    

    DEBUGGING Follow these three steps to debug any oauth application

    1. Make sure you have read https://developers.google.com/accounts/docs/OAuth2 and also the appropriate sub-page (webapp, javascript, etc) depending on which flavour of oauth you are using. You won't get very far debugging your app if you don't understand what it's doing.

    2. Use the Oauth Playground at https://developers.google.com/oauthplayground/ to walk through the Oauth steps and ultimately make a Google API call. This will confirm your understanding and show you what the http calls and responses look like

    3. Use tracing/logging/proxy etc to trace the actual http traffic from your app. Compare this with what you observed in step 2. This should show you where the problem lies.

    这篇关于无法刷新PHP中的OAuth2令牌,无效的授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆