Working with G Suite Admin SDK

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.