-->

Unable to refresh access token : response is “unau

2019-09-15 12:21发布

问题:

First of all, I've read the other questions with similar subjects that I've seen on SO. The solutions there tend to be issues around using credentials copied from elsewhere, so I don't think they apply.

I'm working on a PHP web app that syncs data to a Google Calendar. The OAuth flow works perfectly to start with - I obtain a token, exchange it for an access token, and can call APIs successfully. I store the access token, which includes the refresh token as a subkey, for future reference.

However, once the token expires, things start to go wrong. Calling the authorize API function returns no errors, but when I try to obtain data from the calendar service, I get an error "unauthorized_client".

If I try refreshing the token, using the fetchAccessTokenWithRefreshToken call in the Google PHP library, I get the same response. The RefreshToken passed is the same one returned in earlier calls, and the client object that I'm using to send the call is set up with the same key/secret/access_token as before, so I'm really not sure what's going on. Checking in my Google settings, the app is still listed as authorized.

I can post some code in the hope that I'm making a rookie error, but I imagine that it's more likely that a call somewhere is not being constructed correctly - or indeed that I've misunderstood the OAuth mechanism. Can anyone point me either to the a glaring code error, or else give me ideas for how to debug from here? The calls are made server-side by the PHP library, so I can't inspect them using the browser inspector - I've wondered about setting up Fiddler or similar perhaps?

Code samples:

    $client = getClient($client_id, $client_secret);

    try {
        $client->setAccessToken($access_token);
        $authReturn = $client->authorize();
    } catch (\Exception $e) {
        // Error handling code omitted for brevity
    }

    $service = new \Google_Service_Calendar($client);
    try {
        $calendar_list = $service->calendarList->listCalendarList();
    }
    } catch (\Google_Service_Exception $gse) {
        // unauthorized_client exception firing here
    }

the getClient function is:

function getClient($client_id = null, $client_secret = null, $redirect_url = null) {
$scope = implode(' ', array(\Google_Service_Calendar::CALENDAR));
$client = new \Google_Client();
$client->setAccessType('offline'); // default: offline
$client->setScopes($scope);
$client->setApplicationName(EVENT_GCAL_APPNAME);
$client->setClientId(isset($client_id) ? $client_id : EVENT_GCAL_CLIENTID_DEFAULT);
$client->setClientSecret(isset($client_secret) ? $client_secret : EVENT_GCAL_CLIENTSECRET_DEFAULT);
if (!empty($redirect_url)) {
    $client->setRedirectUri($redirect_url);
}

return $client;     

}

when the error fires, I then try this:

$refreshResult = $client->fetchAccessTokenWithRefreshToken($access_token['refresh_token']);