无法使用 PHP google/apiclient 库模拟服务帐户

问题描述 投票:0回答:1

我正在尝试使用服务帐户获取电子表格,并模拟同一帐户(如果我模拟具有所有者角色的普通帐户,则有效),但我收到错误:

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"                          
    }                                                        
  }                                                          
   
  • 我读了很多书,我知道你必须为该帐户设置一些角色才能像我一样工作(我还添加了更多测试):

$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');
  • 我的service_account.json只是从密钥选项卡下载的json:
{
  "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"
}
php google-cloud-platform service-accounts impersonation google-cloud-iam
1个回答
0
投票

您不需要使用模拟。仅供参考:您使用的服务帐户正在尝试冒充自身。这是没有意义的。您还调用了用于 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');
© www.soinside.com 2019 - 2024. All rights reserved.