Hide
Google Drive Web APIs

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. Go to the Google Developers Console.
  2. Select a project, or create a new one.
  3. In the sidebar on the left, expand APIs & auth. Next, click APIs. In the list of APIs, make sure the status is ON for the Drive API.
  4. In the sidebar on the left, select Credentials.

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. Under the OAuth heading, select Create new Client ID.
  2. When prompted, select Service Account and click Create Client ID.
  3. A dialog box appears. To proceed, click Okay, got it.

If you already have a service account, you can generate a new key by clicking the appropriate button beneath the existing service-account credentials table.

If you haven't done so already, create your OAuth 2.0 credentials by clicking Create new Client ID under the OAuth heading. Next, look for your application's client ID and client secret in the relevant table. You may also create and edit redirect URIs from this page.

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/contrib/Google_DriveService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();

$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com';
$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_DriveService service object.
 */
function buildService($userEmail) {
  $key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
  $auth = new Google_AssertionCredentials(
      SERVICE_ACCOUNT_EMAIL,
      array(DRIVE_SCOPE),
      $key);
  $auth->sub = $userEmail;
  $client = new Google_Client();
  $client->setUseObjects(true);
  $client->setAssertionCredentials($auth);
  return new Google_DriveService($client);
}

?>

.NET

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Drive.v2;
using Google.Apis.Util;

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);

    var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
    {
      ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
      Scope = DriveService.Scopes.Drive.GetStringValue(),
      ServiceAccountUser = userEmail,
    };
    var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);

    return new DriveService(auth);
  }
}

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.

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.