Google客户端刷新令牌只能使用一次

时间:2019-07-10 09:16:07

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

我正在使用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');才能使初始令牌包含刷新令牌。

1 个答案:

答案 0 :(得分:0)

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