我按照这个例子在我的PHP应用程序和Google Cloud API之间获得服务器到服务器的访问, https://developers.google.com/api-client-library/php/auth/service-accounts。 特别是,我需要访问驱动器 API。
当我运行应用程序时,虽然我收到以下错误:
Google_Service_Exception : {
"error": "unauthorized_client",
"error_description": "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested."
}
这是我所做的:
- 创建了 GCP 项目
- 向项目中添加了一个服务帐户,具有域范围的委派和一组密钥
- 在项目中启用了 Google 云端硬盘 API
- 在我的 G Suite 帐号中的"管理 API 客户端访问权限"下,我添加了服务帐号的客户端 ID,并获得了以下权限 https://www.googleapis.com/auth/drive
我错过了一步吗?
这是我的代码:
putenv('GOOGLE_APPLICATION_CREDENTIALS=my_storage/secure/my-app-service-account.json');
$client = new Google_Client();
$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->useApplicationDefaultCredentials();
$client->setSubject('my_email@my_domain.com');
$drive = new Google_Service_Drive($client);
echo $drive->about->get();
该示例不包括setScopes()
调用,但是如果没有它,我遇到了与范围相关的错误。 (该示例不是基于驱动器 API,因此在这种情况下可能不需要它?
更新:在 GCP 的 IAM 设置中,我将服务帐户的电子邮件地址添加为项目所有者,但这没有任何区别。
我发现了问题。
在上面的setScopes()
调用中,传递的值需要与在 G Suite 中设置客户端时给出的值相同,在本例中 https://www.googleapis.com/auth/drive