Google API service account authorization failed

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, refresh the page again and again after 5-10 times), I get a Google_Service_Exception with the message unauthorized_client: Client is unauthorized to retrieve access tokens using this method . The error occurs only if the code $this->drive_service->files->listFiles() . This does not happen if I use the service account directly, and not using setSubject() to impersonate another user.

  $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?

Updated February 21, 2017. The error is no longer interrupted, it happens every time, so I can no longer connect to a regular account at all through the service account.

Update March 10, 2017. It seems that this is a misunderstanding of the user. A service account must be granted "domain authority" to impersonate users of that domain โ€” something I did not do. I simply allowed the client to access the user account as described here .

+6
source share
2 answers

I do not know why your error occurs periodically, but I understand that in order to impersonate a user, you must provide access to the service account .

0
source

I saw this error intermittently when only the created account was created. In his opinion, adding a 10 second delay before trying to create a service fixes the problem.

0
source

Source: https://habr.com/ru/post/1014503/


All Articles