I want to create a google workspace user for my organization from PHP google library, but my code show a 403 error:
{ "error": { "code": 403, "message": "Not Authorized to access this resource/api", "errors": [ { "message": "Not Authorized to access this resource/api", "domain": "global", "reason": "forbidden" } ] } }
I following these steps:
$service->users->listUsers( $optParams );
Grant Owner and Admin Security access to the service account principal:
Add the same scopes of my code in the Domain-wide Delegation option in the Google Workspace Admin Console
This is my code:
public function getClient() { $KEY_FILE_LOCATION = FCPATH . '/assets/api/useraccounts/user-accounts.json'; $client = new Google_Client(); $client->setAuthConfig($KEY_FILE_LOCATION); $client->useApplicationDefaultCredentials(); $client->setSubject('email@company.com'); $client->setApplicationName("Google User Accounts"); $client->setScopes([ "https://www.googleapis.com/auth/admin.directory.group.readonly", "https://www.googleapis.com/auth/admin.directory.group.member.readonly", 'https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/admin.directory.user.readonly', 'https://www.googleapis.com/auth/admin.directory.user.security' ]); return $client; } public function create() { $client = $this->google_account->getClient(); $service = new Google_Service_Directory($client); $user = new Google_Service_Directory_User(); $name = new Google_Service_Directory_UserName(); $name->setGivenName('Apple'); $name->setFamilyName('Test'); $user->setName($name); $user->setHashFunction("MD5"); $user->setPrimaryEmail("apply.test@company.com"); $user->setPassword(hash("md5","Apple2024")); try { $createUserResult = $service->users->insert($user); var_dump($createUserResult); } catch (Exception $e) { echo $e->getMessage(); } }
What could it be? Do I need another scope or add another role in my service account?
I found the solution:
The account in this parameter:
$client->setSubject('email@company.com');
MUST to have admin privileges to manage accounts. So I had to ask our Google Workspace Administrator to make this change from his Console.