当我尝试使用服务器到服务器身份验证调用Google Directory API时,收到错误消息"未授权访问此资源/ api"。
我做了什么:
$serviceAccountName = 'XXXXXXXXXXX@developer.gserviceaccount.com';
$scopes = 'https://www.googleapis.com/auth/admin.directory.group';
$privateKeyFile = dirname(__FILE__).'/../certs/googleapi-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName('API Project');
$client->setScopes($scopes);
$cred = new Google_Auth_AssertionCredentials($serviceAccountName, $scopes, file_get_contents($privateKeyFile));
$client->setAssertionCredentials($cred);
$client->getAuth()->refreshTokenWithAssertion();
$req = new Google_Http_Request("https://www.googleapis.com/admin/directory/v1/groups/group-id@example.com/members?maxResults=1000");
$val = $client->getAuth()->authenticatedRequest($req);
var_dump($client->getAuth()->getAccessToken());
var_dump($val->getResponseBody());
{"错误":{"错误":[{"域名":"全球","原因&#34 ;:"禁止","消息":"未授权访问此资源/ api" },"代码":403,"消息":"未授权访问此资源/ api" }}
当我尝试使用我的PHP脚本中的访问密钥在Google OAuth操场上执行相同的请求时出现同样的错误。我是否必须在开发人员控制台的某处激活对该服务帐户的组数据的访问权限?
答案 0 :(得分:0)
除了授予服务帐户客户端ID访问Google Apps控制台中指定范围的权限外,您还需要告知服务帐户模拟Google Apps域中的超级管理员用户:
$auth->sub = $adminEmail;
出于某种原因,Admin SDK文档不包含PHP示例,但Google Drive文档中的instantiating a service account示例代码。
答案 1 :(得分:0)
我通过反复试验发现删除" admin。"来自范围使其有效(除了上述有关遵循这些步骤的所有内容:https://developers.google.com/drive/web/delegation#delegate_domain-wide_authority_to_your_service_account)。
$cs = json_decode(file_get_contents(<MY SECRET PATH> . 'client_secrets.json'), true);
$cs = $cs['web'];
$cred = new Google_Auth_AssertionCredentials(
$cs['client_email'], //why do they call this "service account name" ? Misleading >:(
array(
'https://www.googleapis.com/auth/directory.user',
'https://www.googleapis.com/auth/directory.group',
'https://www.googleapis.com/auth/directory.group.member'
),
$key,
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
'<MY EMAIL IN THE DOMAIN>' //_my_ email as an user with admin rights
);