Perform G Suite Domain-Wide Delegation of Authority

In enterprise applications you may want to programmatically access a user's data without any manual authorization on their part. In G Suite domains, the domain administrator can grant third-party applications with domain-wide access to its users' data — this is referred as domain-wide delegation of authority. To delegate authority this way, domain administrators can use service accounts with OAuth 2.0.

Create the service account and its credentials

You need to create a service account and its credentials. During this procedure you need to gather information that will be used later for the G Suite domain-wide delegation of authority and in your code to authorize with your service account. The three items you need are your service account’s:

  • Client ID.
  • Private key file.
  • Email address.
  1. Open the Service accounts page. If prompted, select a project.
  2. Click Create service account.
  3. In the Create service account window, type a name for the service account, and select Furnish a new private key and Enable Google Apps Domain-wide Delegation. Then click Create.

Your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of this key. You are responsible for storing it securely.

  1. From the Credentials page, click Create credentials > OAuth client ID to create your OAuth 2.0 credentials or Create credentials > Service account key to create a service account.
  2. If you created an OAuth client ID, then select your application type.
  3. Fill in the form and click Create.

Your application's client IDs and service account keys are now listed on the Credentials page. For details, click a client ID; parameters vary depending on the ID type, but might include email address, client secret, JavaScript origins, or redirect URIs.

After downloading the file and closing the dialog, you will be able to get the service account's email address and client ID.

You should now have gathered your service account's Private Key file, Client ID and email address. You are ready to delegate domain-wide authority to your service account.

Delegate domain-wide authority to your service account

The service account that you created needs to be granted access to the G Suite domain’s user data that you want to access. The following tasks have to be performed by an administrator of the G Suite domain:

  1. Go to your G Suite domain’s Admin console.
  2. Select Security from the list of controls. If you don't see Security listed, select More controls from the gray bar at the bottom of the page, then select Security from the list of controls.
  3. Select Advanced settings from the list of options.
  4. Select Manage API client access in the Authentication section.
  5. In the Client name field enter the service account's Client ID.
  6. In the One or More API Scopes field enter the list of scopes that your application should be granted access to (see image below). For example if you need domain-wide access to Users and Groups enter: https://www.googleapis.com/auth/admin.directory.user, https://www.googleapis.com/auth/admin.directory.group
  7. Click the Authorize button.

Your service account now has domain-wide access to the Google Admin SDK Directory API for all the users of your domain. You are ready to instantiate an authorized Admin SDK Directory service object on behalf of your G Suite domain's users.

Instantiate an Admin SDK Directory service object

This section shows how to instantiate an Admin SDK Directory service object and then authorize it to make API requests using OAuth 2.0 and your service account's credentials to perform G Suite Domain-wide delegation. You should now have the service account's private key file in either PKCS #12 format (if using Java or Python) or JSON format (if using Go) and the email of the service account.

Java

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.admin.directory.Directory;
import com.google.api.services.admin.directory.DirectoryScopes;
...

/** Email of the Service Account */
private static final String SERVICE_ACCOUNT_EMAIL = "<some-id>@developer.gserviceaccount.com";

/** Path to the Service Account's Private Key file */
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/path/to/<public_key_fingerprint>-privatekey.p12";

/**
 * Build and returns a Directory service object authorized with the service accounts
 * that act on behalf of the given user.
 *
 * @param userEmail The email of the user. Needs permissions to access the Admin APIs.
 * @return Directory service object that is ready to make requests.
 */
public static Directory getDirectoryService(String userEmail) throws GeneralSecurityException,
    IOException, URISyntaxException {
  HttpTransport httpTransport = new NetHttpTransport();
  JacksonFactory jsonFactory = new JacksonFactory();
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(httpTransport)
      .setJsonFactory(jsonFactory)
      .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
      .setServiceAccountScopes(DirectoryScopes.ADMIN_DIRECTORY_USERS)
      .setServiceAccountUser(userEmail)
      .setServiceAccountPrivateKeyFromP12File(
          new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
      .build();
  Directory service = new Directory.Builder(httpTransport, jsonFactory, null)
      .setHttpRequestInitializer(credential).build();
  return service;
}

Python

from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

# Email of the Service Account
SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com'

# Path to the Service Account's Private Key file
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12'

def create_directory_service(user_email):
    """Build and returns an Admin SDK Directory service object authorized with the service accounts
    that act on behalf of the given user.

    Args:
      user_email: The email of the user. Needs permissions to access the Admin APIs.
    Returns:
      Admin SDK directory service object.
    """

    credentials = ServiceAccountCredentials.from_p12_keyfile(
        SERVICE_ACCOUNT_EMAIL,
        SERVICE_ACCOUNT_PKCS12_FILE_PATH,
        'notasecret',
        scopes=['https://www.googleapis.com/auth/admin.directory.user'])

    credentials = credentials.create_delegated(user_email)

    return build('admin', 'directory_v1', credentials=credentials)

Go

import (
        "fmt"
        "io/ioutil"
        "golang.org/x/net/context"
        "golang.org/x/oauth2/google"
        "google.golang.org/api/admin/directory/v1"
)

// Path to the Service Account's Private Key file
var ServiceAccountFilePath := '/path/to/<public_key_fingerprint>-privatekey.json'

// Build and returns an Admin SDK Directory service object authorized with
// the service accounts that act on behalf of the given user.
// Args:
//    user_email: The email of the user. Needs permissions to access the Admin APIs.
// Returns:
//    Admin SDK directory service object.
func CreateDirectoryService(userEmail string) *Service {
        jsonCredentials, err := ioutil.ReadFile(ServiceAccountFilePath)
        if err != nil {
            panic(fmt.Sprintf("error reading credentials from file: %v", err))
        }

        config, err := google.JWTConfigFromJSON(jsonCredentials, admin.AdminDirectoryUserScope)
        if err != nil {
                panic(fmt.Sprintf("Unable to parse client secret file to config: %v", err))
        }
        config.Subject = userEmail

        ctx := context.Background()

        client := config.Client(ctx)

        srv, err := admin.New(client)
        if err != nil {
                panic(fmt.Sprintf("Unable to create directory service %v", err))
        }
        return srv

Now that you are authorized and have instantiated an Admin SDK Directory service, have a look at the next steps.

Next steps

Once you are comfortable authorizing Admin SDK Directory API requests, you're ready to manage users and perform any of the other operations described in our Developer's Guides. You can learn more about available API methods in the API Reference.

Send feedback about...

Directory API
Directory API