我正在使用服务帐户来委派域范围的安全性,以便通过 Directory API 和 PHP 客户端库从我们的 Google Apps for Education 实例中提取用户列表。
我相当确定我的服务帐户具有所有正确的安全性,因为它能够使用API 参考的“试用”功能提取列表。
所以,在这一点上,一切都指向我的代码的问题,但我似乎无法弄清楚在哪里:
<?php
require 'vendor/autoload.php';
$clientEmail = '<>@developer.gserviceaccount.com';
$privateKey = file_get_contents(__DIR__ . '/access.p12');
$scopes = array(
'https://www.googleapis.com/auth/admin.directory.user.readonly',
);
$credentials = new Google_Auth_AssertionCredentials($clientEmail, $scopes, $privateKey);
$credentials->sub = 'service.account@my.domain';
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired())
{
$client->getAuth()->refreshTokenWithAssertion();
}
$directory = new Google_Service_Directory($client);
$result = $directory->users->listUsers(array('domain' => 'my.domain'));
var_dump($result);
上面的代码抛出以下错误:
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: ' in C:\wamp\www\quick\vendor\google\apiclient\src\Google\Auth\OAuth2.php on line 358
Google_Auth_Exception: Error refreshing the OAuth2 token, message: '{
"error" : "access_denied",
"error_description" : "Requested client not authorized."
}' in C:\wamp\www\quick\vendor\google\apiclient\src\Google\Auth\OAuth2.php on line 358
Call Stack:
0.0010 132792 1. {main}() C:\wamp\www\quick\index.php:0
0.0260 1060248 2. Google_Auth_OAuth2->refreshTokenWithAssertion() C:\wamp\www\quick\index.php:18
0.9230 1163560 3. Google_Auth_OAuth2->refreshTokenRequest() C:\wamp\www\quick\vendor\google\apiclient\src\Google\Auth\OAuth2.php:309