我正在尝试使用服务帐户获取电子表格,并模拟同一帐户(如果我模拟具有所有者角色的普通帐户,则有效),但我收到错误:
In REST.php line 134:
{
"error": {
"code": 403,
"message": "The caller does not have permission",
"errors": [
{
"message": "The caller does not have permission",
"domain": "global",
"reason": "forbidden"
}
],
"status": "PERMISSION_DENIED"
}
}
还使用了域范围委托并授予此帐户使用权限https://www.googleapis.com/auth/spreadsheets
我使用 php 库的客户端配置是类似的,重要部分在这里:
$googleClient = new Google_Client();
$googleClient->setApplicationName('app name');
$googleClient->setScopes('https://www.googleapis.com/auth/spreadsheets');
$googleClient->setAccessType('offline');
$googleClient->setAuthConfig('config/credentials/service_account.json');
$googleClient->setSubject('[email protected]');
$service = new Google_Service_Sheets($googleClient);
$response = $service->spreadsheets->get('myspreadhseetID');
{
"type": "service_account",
"project_id": "myprojectname",
"private_key_id": "myprivatekeyid",
"private_key": "-----BEGIN PRIVATE KEY-----\n KEY HERE \n-----END PRIVATE KEY-----\n",
"client_email": "[email protected]",
"client_id": "myclientId",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/myserviceaccount%myserviceaccount.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}
您不需要使用模拟。仅供参考:您使用的服务帐户正在尝试冒充自身。这是没有意义的。您还调用了用于 OAuth 用户身份验证的函数。
注意:我没有检查您是否需要额外的范围。
要做的事情:从服务账户中删除所有 IAM 角色,最重要的是
Owner
以及所有包含 service account
的角色。其中大多数允许服务帐户使用另一个服务帐户,这是危险的。我认为您根本不需要任何 IAM 角色。 Google Sheets 不属于 Google Cloud,也不使用 Google Cloud IAM。相反,Google 表格使用 OAuth 访问令牌以及 OAuth 范围授予的权限。
使用以下类型的代码:
$googleClient = new Google_Client();
$googleClient->setScopes('https://www.googleapis.com/auth/spreadsheets');
$googleClient->setAuthConfig('config/credentials/service_account.json');
$service = new Google_Service_Sheets($googleClient);
$response = $service->spreadsheets->get('myspreadhseetID');