Search code examples
phpgoogle-apigoogle-api-php-clientgoogle-admin-sdk

Google SDK API - update Workspace user profile data by service account (Not Authorized to access this resource/api)


I am trying to sync our user profiles from our internal SaaS to Google Workspace user profiles. Especially (gender, phone, jobTitle, department). After a long reading, I found out that it is not possible to do by OAuth in the Google cloud project, but it is necessary to create a service account. I have created it, but I am still getting responses Not Authorized to access this resource/api.

  • The Domain-wide Delegation is enabled.
  • Admin SDK API is enabled.
  • API client access with scope "https://www.googleapis.com/auth/admin.directory.user" is enabled in Workspace security.

Permission of service account: enter image description here

Code:

        $config = __DIR__ . '/project-users.json';

        $client = new \Google\Client();
        $client->setApplicationName('project-users');
        $client->setAuthConfig($config);
        $client->addScope(Google_Service_Directory::ADMIN_DIRECTORY_USER);
        $client->setSubject('admin@domain.com');
        $client->setAccessType('offline');

        $gsdService = new \Google\Service\Directory($client);
        
        $googleUser = new \Google\Service\Directory\User();
        // Gender
        $gender = new \Google\Service\Directory\UserGender();
        $gender->setType('male');
        // Phone
        $phone = new \Google\Service\Directory\UserPhone();
        $phone->setType('mobile');
        $phone->setValue('123456789');
        $googleUser->setPhones([$phone]);
        // jobTitle and department
        $organization = new \Google\Service\Directory\UserOrganization();
        $organization->setPrimary(TRUE);
        $organization->setTitle('Lead Developer');
        $organization->setDepartment('Dev');
        $googleUser->setOrganizations([$organization]);
        
        $gsdService->users->update('fname.lname@domain.com', $googleUser);

Solution

  • When using a service account with domain-wide delegation you need to impersonate a user who has the necessary authorization

    • The Directory API method users.update can only be executed by domain admins with the respective role / permissions.
    • See how to make a user an admin.
    • If in doubt, you can test with the [Try this API](Try this API) authorized as 'admin@domain.com' to verify either this user has the necessary permissions.