php - 谷歌服务器到服务器 OAuth2 PHP 示例不起作用
问题描述
我正在按照此示例在我的 PHP 应用程序和 Google Cloud API 之间进行服务器到服务器访问, https://developers.google.com/api-client-library/php/auth/service-accounts。特别是,我需要访问 Drive 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 Drive 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()
调用,但是没有它我得到了与范围相关的错误。(该示例不是基于 Drive API,所以在这种情况下可能不需要它?)
更新:在 GCP 的 IAM 设置中,我将服务帐户的电子邮件地址添加为项目所有者,但这没有任何区别。
解决方案
我发现了问题。
在setScopes()
上面的调用中,传递的值需要与在 G Suite 中设置客户端时给出的值相同,在本例中为https://www.googleapis.com/auth/drive
推荐阅读
- angular - 加载块模块失败:升级到 Angular 7
- php - 向长时间运行的 PHP 脚本发送同步信号/消息
- c# - 获取项目等于实体框架列表中的元素之一的诊所
- r - r 循环/函数从列表中查找匹配项
- flutter - Flutter中缓存大小的最大限制
- azure-active-directory - Azure Active Directory 是否适合 Internet 应用程序
- arrays - 如何在 TypeScript 中对对象数组进行排序
- python - 如何调整管道内随机森林分类器中的参数?
- python - 为什么删除字符串和更新数据集的代码不起作用?
- python - Python Tkinter GUI 执行 python 脚本错误