google-api-php-client: Sporadic "unauthorized_client" Issues - Service Account
I am using the google-api-php-client client to connect to Google Drive using a Service Account. Most of the time it works, but every so often (say if I sit here an refresh the page over and over it’s every 5th to 10th time), I receive a Google_Service_Exception
with the message unauthorized_client: Client is unauthorized to retrieve access tokens using this method
. The error only occurs if the $this->drive_service->files->listFiles()
code is present.
$this->client = new Google_Client();
$this->client->useApplicationDefaultCredentials();
$this->client->addScope("https://www.googleapis.com/auth/drive");
$this->client->setSubject('xxxx');
$this->drive_service = new Google_Service_Drive($this->client);
$files = $this->drive_service->files->listFiles();
Any thoughts? There are no hits for this error message when I search for it.
Update: Seems to be specific to client->setSubject(), if I remove that and use the Service Account itself, the error never appears.
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 16 (1 by maintainers)
I’ve had the same issue with the Calendar API. My code is wrapped inside a helper class, but should still be useful…
$this->client = new \Google_Client;
$this->client->setAuthConfig( $this->config->secret );
$this->client->setScopes( [ \Google_Service_Calendar::CALENDAR_READONLY ] );
$this->client->setSubject( $this->config->impersonateUser );
The problem here seems to be the scope. Changing from this…
$this->client->setScopes( [ \Google_Service_Calendar::CALENDAR_READONLY ] );
…to this…
$this->client->setScopes( [ \Google_Service_Calendar::CALENDAR ] );
…appears to work. At the least, it’s able to access at least one calendar on the domain, and is not throwing the credential error. I have no idea why a read-only scope wouldn’t work, and this does seem kind of like a kludge to make things work this way.
I hope this helps someone else who’s facing the same issue.