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 known 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 credentials

The following steps create a service account and its credentials, which are required for G Suite domain-wide delegation of authority. Your code uses the credentials created here to authorize the actions the service account takes.

  1. Open the Service accounts page. If prompted, select a project.
  2. Click Create Service Account, enter a name and description for the service account. You can use the default service account ID, or choose a different, unique one. When done click Create.
  3. The Service account permissions (optional) section that follows is not required. Click Continue.
  4. On the Grant users access to this service account screen, scroll down to the Create key section. Click Create key.
  5. In the side panel that appears, select the format for your key: JSON is recommended.
  6. Click Create. Your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of this key. For information on how to store it securely, see Managing service account keys.
  7. Click Close on the Private key saved to your computer dialog, then click Done to return to the table of your service accounts.

To enable G Suite domain-wide delegation, follow these steps:

  1. Locate the newly-created service account in the table. Under Actions, click then Edit.
  2. In the service account details, click Show domain-wide delegation, then ensure the Enable G Suite Domain-wide Delegation checkbox is checked.
  3. If you haven't yet configured your app's OAuth consent screen, you must do so before you can enable domain-wide delegation. Follow the on-screen instructions to configure the OAuth consent screen, then repeat the above steps and re-check the checkbox.
  4. Click Save to update the service account, and return to the table of service accounts. A new column, Domain-wide delegation, can be seen. Click View Client ID, to obtain and make a note of the client ID.

Delegate domain-wide authority to your service account

To access user data on a G Suite domain, the service account that you created needs to be granted access by a super administrator for the domain. For more information about domain-wide delegation, see Control G Suite API access with domain-wide delegation.

To delegate domain-wide authority to a service account:

  1. From your G Suite domain’s Admin console, go to Main menu > Security > API controls.
  2. In the Domain wide delegation pane, select Manage Domain Wide Delegation.
  3. Click Add new.
  4. In the Client ID field, enter the client ID obtained from the service account creation steps above.
  5. In the OAuth Scopes field, enter a comma-delimited list of the scopes required for your application (for a list of possible scopes, see Authorize requests).

    For example, if you require domain-wide access to Users and Groups enter: https://www.googleapis.com/auth/admin.directory.user, https://www.googleapis.com/auth/admin.directory.group

  6. Click Authorize.

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

The following examples make use of your service account's email address and private key file. The Java and Python versions use a P12-formatted key file, while the Go example uses a JSON-formatted key file.

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"

  admin "google.golang.org/api/admin/directory/v1"
  "google.golang.org/api/option"
)

// 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) (*admin.Service, error) {
  ctx := context.Background()

  jsonCredentials, err := ioutil.ReadFile(ServiceAccountFilePath)
  if err != nil {
    return nil, err
  }

  config, err := google.JWTConfigFromJSON(jsonCredentials, admin.AdminDirectoryUserScope)
  if err != nil {
    return nil, fmt.Errorf("JWTConfigFromJSON: %v", err)
  }
  config.Subject = userEmail

  ts := config.TokenSource(ctx)

  srv, err := admin.NewService(ctx, option.WithTokenSource(ts))
  if err != nil {
    return nil, fmt.Errorf("NewService: %v", err)
  }
  return srv, nil
}

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.