Google Drive SDK

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.

If you haven't already registered your application with the Google Developers Console, then set up a project and application in the Developers Console. The system guides you through the process of choosing or creating a project and registering a new application, and it automatically activates the API for you.

If you've already registered your application with the Developers Console, then follow this procedure instead:

  1. Go to the Google Developers Console.
  2. Select a project.
  3. In the sidebar on the left, select APIs & auth. 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 application's credentials page.

To set up a service account, select Create New Client ID. Specify that your application type is service account, and then select Create Client ID. A dialog box appears; to proceed, select Okay, got it. (If you already have a service account, you can add a new key by selecting Generate new key beneath the existing service-account credentials. A dialog box appears; to proceed, select Okay, got it.)

To find your application's client ID and client secret, and set a redirect URI, expand the OAuth 2.0 Client ID section.

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.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
...

/** 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, URISyntaxException {
  HttpTransport httpTransport = new NetHttpTransport();
  JacksonFactory jsonFactory = new JacksonFactory();
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(httpTransport)
      .setJsonFactory(jsonFactory)
      .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
      .setServiceAccountScopes(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.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.