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. It does not occur if I use the Service Account directly rather than 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?
Update Feb 21, 2017: The error is no longer intermittent, it happens every time, so I can no longer connect at all to a regular account through a service account.
Update March 10, 2017: It seems as though this is a user misunderstanding. The service account must be given "domain-wide authority" in order to impersonate users of that domain - something I have not done. I had simply authorized a client to access the users account as described here.
I don't know why your error happens periodically but my understanding is that to impersonate an user, you must grant the service account access.
I've seen this error intermittently when the account that's being impersonated is newly created. By the looks of it, adding a 10 second delay before trying to create the service eliminates the problem.
来源:https://stackoverflow.com/questions/41903578/google-api-service-account-authorization-error