Google目录API和PHP:请求中未经授权的客户端或范围


Google Directory API and PHP: Unauthorized client or scope in request

我正在使用Google Directory API、oauth2的服务帐户和PHP,从命令行运行。

作为第一步,我只是尝试检索一个用户对象。这是代码:

require_once realpath(__DIR__ . '/../vendor/autoload.php');
session_start();
define('APPLICATION_NAME', 'Directory API PHP Quickstart');
define('SCOPES', implode(' ', 
array(Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY)));
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/XXXXXXXX.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(SCOPES);
$client->setSubject('me@mydomain.com');
$httpClient = $client->authorize();
$response = 
$httpClient->get('https://www.googleapis.com/admin/directory/v1/users/me@mydomain.com');
print $response->getBody();

这是我得到的回应:

Uncaught exception 'GuzzleHttp'Exception'ClientException' with message 'Client error: `POST https://www.googleapis.com/oauth2/v4/token` resulted in a `401 Unauthorized` response:
{
 "error": "unauthorized_client",
 "error_description": "Unauthorized client or scope in request."
}
' in /var/www/feeds/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:107
Stack trace: #0 /var/www/feeds/vendor/guzzlehttp/guzzle/src/Middleware.php(65): GuzzleHttp'Exception'RequestException::create(Object(GuzzleHttp'Psr7'Request), Object(GuzzleHttp'Psr7'Response))
#1 /var/www/feeds/vendor/guzzlehttp/promises/src/Promise.php(203): GuzzleHttp'Middleware::GuzzleHttp'{closure}(Object(GuzzleHttp'Psr7'Response))
#2 /var/www/feeds/vendor/guzzlehttp/promises/src/Promise.php(156): GuzzleHttp'Promise'Promise::callHandler(1, Object(GuzzleHttp'Psr7'Response), Array)
#3 /var/www/feeds/vendor/guzzlehttp/promises/src/TaskQueue.php(61): GuzzleHttp'Promise'Promise::GuzzleHttp'Promise'{closure}()
#4 /var/www/feeds/vendor/guzzlehttp/promis in /var/www/feeds/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 107

在管理控制台>安全>管理API客户端访问中,我输入了具有以下API范围的客户端ID:

View and manage the provisioning of groups on your domain
https://www.googleapis.com/auth/admin.directory.group
View and manage the provisioning of users on your domain
https://www.googleapis.com/auth/admin.directory.user
Groups Settings
https://www.googleapis.com/auth/apps.groups.settings 

我用于主题的帐户('me@mydomain.com')是域上的超级管理员。已为服务帐户启用域范围委派。

我在这里俯瞰什么?如有任何帮助,我们将不胜感激。

检查您是否已在管理控制台中启用API,还检查该服务是否已在Google Project for Admin SDK中启用。