php 库中有一个新函数接近这个,但不允许设置 sub,所以总是给授权失败。所以,首先将 src/Google/Client.php 中的 php 库函数 loadServiceAccountJson 更新为:
public function loadServiceAccountJson($jsonLocation, $scopes)
{
$data = json_decode(file_get_contents($jsonLocation));
if (isset($data->type) && $data->type == 'service_account') {
// Service Account format.
$cred = new Google_Auth_AssertionCredentials(
$data->client_email,
$scopes,
$data->private_key,
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
$data->sub
);
return $cred;
} else {
throw new Google_Exception("Invalid service account JSON file.");
}
}
然后,在您的服务器身份验证 json 文件中的数据中添加一个值 sub:
{
"private_key_id": "removed",
"private_key": "-----BEGIN PRIVATE KEY-----\n-----END PRIVATE KEY-----\n",
"client_email": "removed",
"client_id": "removed",
"redirect_uris":[your urls here],
"type": "service_account",
"sub": "valid.user@google.domain.com"
}
现在,获得授权:
$credentials = $client->loadServiceAccountJson('serverauth.json',"https://www.googleapis.com/auth/admin.directory.user.readonly");
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
其中 serverauth.json 是从您要使用的服务帐户下载的 JSON 密钥文件,并添加了子行。
最后,创建一个 Directory 实例并查询它:
$service = new Google_Service_Directory($client);
$optParams = array(
'domain' => 'google.domain.com',
'orderBy' => 'email',
'viewType' => 'domain_public',
'query' => "givenName:'Joe' familyName:'Schmoe Jr'"
);
$results = $service->users->listUsers($optParams);
$users = $results->getUsers();
print_r($users);