【问题标题】:Google API oauth2 token expires?Google API oauth2 令牌过期了吗?
【发布时间】:2018-02-20 20:52:07
【问题描述】:

我对 google api 和 oauth2 令牌有疑问。

有一个应用程序允许通过 oauth2 令牌将联系人/日历与您的谷歌帐户同步。

当用户第一次想连接他的谷歌帐户时,他需要授予访问权限,然后应用程序正在接收保存的代码/令牌,稍后将用于离线同步。

function getClient($app) 
{       
    $client = new Google_Client();
    $client->setAuthConfig("path_to_secret.json");

    switch($app)
    {
        case 'contacts':
        $client->addScope(Google_Service_Script::WWW_GOOGLE_COM_M8_FEEDS);
        $client->addScope(Google_Service_People::USERINFO_EMAIL);
        break;

        case 'calendar':
        $client->addScope(Google_Service_Calendar::CALENDAR);
        break;

        default:
        throw new Exception('API Callback not defined in setup');
    }

    $client->setAccessType('offline'); // offline access
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setRedirectUri(GOOGLE_APP_URL . $app.'/callback.php');
    return $client;
}

(联系人和日历有不同的标记)

同步脚本:

...
try
{
    $client = getClient('calendar');
    $client->setAccessToken(unserialize($accessToken));
    $http = $client->authorize();

    $service = new Google_Service_Calendar($client);

    ...
}

$accessToken 是一个序列化的字符串,如:

a:5:{s:12:"access_token";s:131:"******token_here********";s:10:"token_type";s:6:"Bearer";s:10:"expires_in";i:3598;s:8:"id_token";s:902:"***id_token****";s:7:"created";i:1505178047;}

这是第一次和几次,但在一段时间(小时)后出现错误:

错误: {"error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" }}

我做错了什么?

有趣的是,联系人同步一直都可以正常工作(访问令牌与日历同步具有相同的属性)

【问题讨论】:

  • 你可能需要一个刷新令牌
  • 您使用什么版本的 Google API 客户端?
  • 2.0版
  • 我没有获得带有访问令牌的刷新令牌。在联系人同步中,我也没有刷新令牌,而且它一直工作正常。谷歌日历的工作方式是否不同?
  • 如果我没记错的话,Google API 客户端可能有一个内部机制,如果需要,它会自动刷新access_token。当你通过代码授权任何用户时——你可能有refresh_token,它允许你在最后一个过期时获得新的access_token(只是访问类型=='离线')。在出现此错误之前您做了哪些更改?

标签: php oauth-2.0 google-api google-calendar-api


【解决方案1】:

好的,可以解决 - refresh_token 仅是第一次提供,所以当我多次测试它时,我没有得到刷新令牌。 当我撤销https://myaccount.google.com/u/0/permissions 的访问权限并再次连接时,我也收到了刷新令牌。我认为现在它会正常工作

【讨论】:

    猜你喜欢
    • 2012-11-30
    • 1970-01-01
    • 2019-05-25
    • 2018-04-07
    • 2016-08-03
    • 1970-01-01
    • 2021-08-27
    • 2016-02-15
    • 2018-04-26
    相关资源
    最近更新 更多