Hide

Perform Google Apps Domain-Wide Delegation of Authority

In enterprise applications you may want to programmatically access users data without any manual authorization on their part. In Google Apps domains, the domain administrator can grant to third party applications 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 three items that will be used later for the Google Apps domain-wide delegation of authority and in your code to authorize with your service account. These three items are your service account’s:

  • Client ID.
  • Private key file.
  • Email address.

To get started using Drive API, you need to first create or select a project in the Google Developers Console and enable the API. Using this link guides you through the process and activates the Drive API automatically.

Alternatively, you can activate the Drive API yourself in the Developers Console by doing the following:

  1. Open the Credentials page.

In either case, you end up on the Credentials page and can create your project's credentials from here.

To set up a new service account, do the following:

  1. Click Add credentials > Service account.
  2. Choose whether to download the service account's public/private key as a standard P12 file, or as a JSON file that can be loaded by a Google API client library.

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.

From the Credentials page, click Add credentials > OAuth 2.0 client ID to create your OAuth 2.0 credentials or Add credentials > Service account to create a service account.

Next, if you created an OAuth 2.0 client ID, select your application type.

Your application's client IDs are now listed. You can click each client ID for details; parameters vary depending on the ID type, but might include email address, client secret, JavaScript origins, and 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 now needs to be granted access to the Google Apps domain’s user data that you want to access. The following tasks have to be performed by an administrator of the Google Apps domain:

  1. Go to your Google Apps 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 third party OAuth 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 the Google Drive API and the Google Calendar API enter: https://www.googleapis.com/auth/drive, https://www.googleapis.com/auth/calendar
  7. Click the Authorize button.

Your service account now has domain-wide access to the Google Drive API for all the users of your domain, and potentially the other APIs you’ve listed such as the Calendar API in the example above. You are ready to instantiate an authorized Drive service Object on behalf of your Google Apps domain's users.

Instantiate a Drive service object

This section shows how to instantiate a Drive service object and then authorize it to make API requests using OAuth 2.0 and your service accounts' credentials to perform Google Apps Domain-wide delegation. You should now have the service account's private key file in a PKCS #12 format 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.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;

import java.util.Arrays;
...

/** 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 Drive service object authorized with the service accounts
 * that act on behalf of the given user.
 *
 * @param userEmail The email of the user.
 * @return Drive service object that is ready to make requests.
 */
public static Drive getDriveService(String userEmail) throws GeneralSecurityException,
    IOException {
  HttpTransport httpTransport = new NetHttpTransport();
  JacksonFactory jsonFactory = new JacksonFactory();
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(httpTransport)
      .setJsonFactory(jsonFactory)
      .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
      .setServiceAccountScopes(Arrays.asList(DriveScopes.DRIVE))
      .setServiceAccountUser(userEmail)
      .setServiceAccountPrivateKeyFromP12File(
          new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
      .build();
  Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
      .setHttpRequestInitializer(credential).build();
  return service;
}

Python

import httplib2
import pprint
import sys

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

"""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 createDriveService(user_email):
  """Build and returns a Drive service object authorized with the service accounts
  that act on behalf of the given user.

  Args:
    user_email: The email of the user.
  Returns:
    Drive service object.
  """
  f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
  key = f.read()
  f.close()

  credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
      scope='https://www.googleapis.com/auth/drive', sub=user_email)
  http = httplib2.Http()
  http = credentials.authorize(http)

  return build('drive', 'v2', http=http)

PHP

<?php

require_once "google-api-php-client/src/Google/Client.php";
require_once "google-api-php-client/src/Google/Service/Drive.php";
require_once "google-api-php-client/src/Google/Service/Oauth2.php";
session_start();

define('DRIVE_SCOPE', 'https://www.googleapis.com/auth/drive');
define('SERVICE_ACCOUNT_EMAIL', '<some-id>@developer.gserviceaccount.com');
define('SERVICE_ACCOUNT_PKCS12_FILE_PATH', '/path/to/<public_key_fingerprint>-privatekey.p12');

/**
 * Build and returns a Drive service object authorized with the service accounts
 * that acts on behalf of the given user.
 *
 * @param userEmail The email of the user.
 * @return Google_Service_Drive service object.
 */
function buildService($userEmail) {
  $key = file_get_contents(SERVICE_ACCOUNT_PKCS12_FILE_PATH);
  $auth = new Google_Auth_AssertionCredentials(
      SERVICE_ACCOUNT_EMAIL,
      array(DRIVE_SCOPE),
      $key);
  $auth->sub = $userEmail;
  $client = new Google_Client();
  $client->setAssertionCredentials($auth);
  return new Google_Service_Drive($client);
}

?>

.NET

using System;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v2;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;

public class MyClass
{

  private const string SERVICE_ACCOUNT_EMAIL = "<some-id>@developer.gserviceaccount.com";
  private const string SERVICE_ACCOUNT_PKCS12_FILE_PATH = @"\path\to\<public_key_fingerprint>-privatekey.p12";

  /// <summary>
  /// Build a Drive service object authorized with the service account
  /// that acts on behalf of the given user.
  /// </summary>
  /// @param userEmail The email of the user.
  /// <returns>Drive service object.</returns>
  static DriveService BuildService(String userEmail)
  {
    X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH,
        "notasecret", X509KeyStorageFlags.Exportable);
    ServiceAccountCredential credential = new ServiceAccountCredential(
        new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
        {
          Scopes = new[] { DriveService.Scope.Drive },
          User = userEmail
        }.FromCertificate(certificate));

    // Create the service.
    var service = new DriveService(new BaseClientService.Initializer()
    {
      HttpClientInitializer = credential,
      ApplicationName = "Drive API Service Account Sample",
    });

    return service;
  }
}

Ruby

require 'google/api_client'

## 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'

##
# Build a Drive client instance authorized with the service account
# that acts on behalf of the given user.
#
# @param [String] user_email
#   The email of the user.
# @return [Google::APIClient]
#   Client instance
def build_client(user_email)
    key = Google::APIClient::PKCS12.load_key(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'notasecret')
    asserter = Google::APIClient::JWTAsserter.new(SERVICE_ACCOUNT_EMAIL,
        'https://www.googleapis.com/auth/drive', key)
    client = Google::APIClient.new
    client.authorization = asserter.authorize(user_email)
    client
end

JavaScript

For security reasons service accounts are not supported in client-side
Javascript. Service accounts for server-side Javascript is not yet
supported.

Note that service accounts' storage quota cannot be upgraded from the initial limit, so it is not good practice to rely on these accounts to own Drive files.

Now that you are authorized and have instantiated a Drive service, have a look at the next steps.

Next steps

Once you are comfortable authorizing Drive API requests, you're ready to upload files and perform any of the other operations described in "Manage Drive Files." You can learn more about available API methods in the API Reference, and you can review our end-to-end Example Apps to examine some working code.

Send feedback about...

Drive REST API