phpgoogle-apigoogle-api-php-clientgoogle-developers-consolegoogle-account

Creating google user in php: Not Authorized to access this resource/api


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:

  1. Create my service account. It works fine with the defined scopes and other endpoints like:

$service->users->listUsers( $optParams );

  1. Grant Owner and Admin Security access to the service account principal: enter image description here

  2. Add the same scopes of my code in the Domain-wide Delegation option in the Google Workspace Admin Console enter image description here

  3. 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?


Solution

  • 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.