There's a new function in the php library that gets close to this, but doesn't allow setting sub, so always gives authorization fails. So, first update the php library function loadServiceAccountJson
in src/Google/Client.php to this:
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.");
}
}
Then, add a value sub to the data in your server auth json file:
{
"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": "[email protected]"
}
Now, obtain authorization:
$credentials = $client->loadServiceAccountJson('serverauth.json',"https://www.googleapis.com/auth/admin.directory.user.readonly");
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
Where serverauth.json is the JSON keyfile downloaded from the service account you want to use, and added the sub line to.
And lastly, create a Directory instance and query it:
$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);
client_secret.json
file was by default set withread only
on mac. I didchmod 777
(gave write permissions) to this file, which fixed the issue. – Mr_Green