I'm trying to get the groups a user is associated with on a google GSuite for Education.
I've started following the tutorial to list all the users related to the association, but I got: error 400 - "message": "Invalid Input.
So far I've created a project, with a service account because I need that there will be no user interaction as the fetch has to be done automatically.
After that I set the account as enabled for G Suite Domain-wide Delegation and put it in the authorized API client with the https://www.googleapis.com/auth/admin.directory.group.readonly and https://www.googleapis.com/auth/admin.directory.user.readonly domains but when I run the code I get the error above
Here's the code:
<?php
require_once './google-api/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/Culturalia.json');
function getGoogleClient() {
return getServiceAccountClient();
}
function getServiceAccountClient() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope([Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY]);
return $client;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
$client = getGoogleClient();
$service = new Google_Service_Directory($client);
// Print the first 10 users in the domain.
$optParams = array(
'customer' => 'my_customer',
'maxResults' => 10,
'orderBy' => 'email',
);
$results = $service->users->listUsers($optParams);
if (count($results->getUsers()) == 0) {
print "No users found.\n";
} else {
print "Users:\n";
foreach ($results->getUsers() as $user) {
printf("%s (%s)\n", $user->getPrimaryEmail(),
$user->getName()->getFullName());
}
}
?>
But my guess it's that is more likely an authorization that I'm missing somewhere, any help would be appreciated.
You might have granted domain-wide delegation to the Service Account (double-check that you've done it using this guide), but you haven't used this delegation to impersonate any account in the domain. That's the part you're missing.
The purpose of granting domain-wide delegation is for the Service Account to be able to access resources on behalf of any account in your domain. You need to specify, though, which account you want to impersonate; otherwise, you're not impersonating anyone, and the Service Account is acting as if you hadn't granted domain-wide delegation at all.
Since the Service Account is technically not part of the domain, you're getting an error when trying to list the domain users.
To impersonate an account, you need to specify its email address when setting up the client
, like this:
$user = "email-address@your-domain";
$client->setSubject($user);