【问题标题】:Google Client Refresh Token only works once谷歌客户端刷新令牌只能使用一次
【发布时间】:2019-07-10 09:16:07
【问题描述】:

我正在使用 Google API 客户端访问 Directory API。我的代码如下:

function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('G Suite Directory API');
    $client->setScopes(Google_Service_Directory::ADMIN_DIRECTORY_USER);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');

    $client->setApprovalPrompt('force');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.

        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            .....
            //this is where google creates the initial token
        }

    }
}

我的问题围绕着这条线:

$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());

当我最初授权客户端时,我得到一个包含刷新令牌的 token.json。一小时后,令牌过期并创建一个新令牌。但是,此新令牌不包括刷新令牌。所以它只会刷新一次,然后在 2 小时后停止工作。

有没有我缺少的设置? 我必须添加 $client->setApprovalPrompt('force'); 才能使初始令牌包含刷新令牌。

【问题讨论】:

  • 刷新令牌过期了?我们已经使用相同的方法运行 Java 应用程序两年了,并且长时间使用相同的令牌,刷新令牌停止为我们工作的唯一原因是在我们正常的失效过程中,我们为安全目的。

标签: javascript google-api google-oauth google-client google-client-login


【解决方案1】:

您应该继续重复使用最初获得的刷新令牌,以便每小时获取新的访问令牌(然后您将在每个 API 请求中使用该令牌)。刷新令牌通常不会过期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 2015-08-01
    • 2021-08-12
    • 2018-12-08
    • 2019-01-11
    • 2015-05-17
    • 2020-08-27
    相关资源
    最近更新 更多