当我尝试使用服务器到服务器身份验证调用 Google Directory API 时,收到错误消息“未授权访问此资源/api”。
我做了什么:
- 在 Google Developers Console 中创建了一个应用程序。
- 下载私钥并查找服务帐户名称。
- 在 API 下激活 Admin SDK。
- 下载 google-api-php-client。
- 编写了以下代码:
$serviceAccountName = '[email protected]';
$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/[email protected]/members?maxResults=1000");
$val = $client->getAuth()->authenticatedRequest($req);
var_dump($client->getAuth()->getAccessToken());
var_dump($val->getResponseBody());
- 执行该小脚本会生成一个有效的访问令牌,有效期为一小时,并显示以下错误消息:
{ "error": { "errors": [ { "domain": "global", "reason": "forbidden", "message": "无权访问此资源/api" } ], "code": 403 , "message": "未授权访问此资源/api" } }
当我尝试使用 PHP 脚本中的访问密钥在 Google OAuth Playground 上执行相同的请求时,出现相同的错误。我是否必须在开发人员控制台中的某个位置激活对该服务帐户的组数据的访问权限?
除了授予服务帐户客户端 ID 访问 Google Apps 控制台中给定范围的权限之外,您还需要告诉服务帐户在您的 Google Apps 域中模拟超级管理员用户:
$auth->sub = $adminEmail;
由于某种原因,Admin SDK 文档不包含 PHP 示例,但有示例代码实例化服务帐户在 Google 云端硬盘文档中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)