The new function in the php library loadServiceAccountJson
doesn't allow setting sub in the Google_Auth_AssertionCredentials
creator, so always gives authorization fails. How do we get the library updated?
The following instructions will allow a working query, in my case to the Admin SDK Directory API:
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, downloaded from the Developer Console/APIs & Auth/Credentials (you'll need to make a Service Account) - name the file 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": "[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();
}
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);