Warning: This article was written in 2018, the content might be out of date.

Working with G Suite Admin SDK

Categories: Web Development

On occasion, you want to build an application to interact with G Suite without logging to the console. The G Suite Admin SDK is a tool for the purpose. 

In authentication, there are two ways to do it. 

  1. Using service account and impersonate an account with administrative access. 
  2. Use OAuth to authenticate access through SDK. (Recommended)

The first option is great for automate tasks, such as generating reports, but not recommended for web app with access from anyone.

Let’s look at how to implement option #2 with Laravel

  1. Use composer to download and include the Admin SDK. composer require google/apiclient:2.0
  2. Create a OAuth 2.0 client ID in https://console.developers.google.com/apis
  3. Place the client_id and client_secret the same way you when setting up Socialite using Google OAuth. 
  4. In the Socialite login code, set scopes that you want the account with administrative access. The Admin SDK scopes are listed in here. For example to retrieve group, group alias, and member information, uses: j

return Socialite::driver(‘google’)
->scopes([ 'https://www.googleapis.com/auth/admin.directory.group.readonly',
])
->redirect();

  • When retrieving user detail after login, store the $user->token somewhere. 

6. Back to using Google client, create a $client as below 

$client = new Google_Client();
$client->setApplicationName('G Suite Directory Demo');
$client->setAccessToken([User Token here]);

$service = new Google_Service_Group($client);
$optParams = array(
'userKey' => 'administrative-account@example.com',
'maxResult' => 10
);
$results = $service->groups->listGroups($optParams);

7. Done

Next | Previous