【发布时间】:2015-07-24 16:46:54
【问题描述】:
php 库loadServiceAccountJson 中的新函数不允许在Google_Auth_AssertionCredentials 创建者中设置sub,所以总是给授权失败。我们如何更新库?
以下说明将允许一个有效的查询,在我的例子中是 Admin SDK Directory API:
首先,将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.");
}
}
然后,将值 sub 添加到服务器身份验证 json 文件中的数据,该文件是从开发人员控制台/API 和身份验证/凭据下载的(您需要创建一个服务帐户) - 将文件命名为 serverauth.json :
{
"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();
}
最后,创建一个 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);
【问题讨论】:
标签: php google-api-php-client google-admin-sdk