Google Workspace ドメイン全体の権限の委任を行う

エンタープライズ アプリケーションでは、ユーザーによる手動の承認なしで、プログラムを使用してユーザーのデータにアクセスしたい場合があります。Google Workspace ドメインでは、ドメイン管理者がドメイン全体のユーザーデータへのアクセス権をサードパーティ アプリケーションに付与できます。これは、ドメイン全体の権限の委任と呼ばれます。このような権限の委任を行うには、ドメイン管理者が OAuth 2.0 のサービス アカウントを使用します。

サービス アカウントと認証情報を作成する

以下の手順で、Google Workspace ドメイン全体の権限の委任に必要となるサービス アカウントと認証情報を作成します。コードでは、ここで作成された認証情報を使用して、サービス アカウントが行う操作を承認してください。

  1. [サービス アカウント] ページを開きます。メッセージが表示されたら、プロジェクトを選択します。
  2. [ サービス アカウントを作成] をクリックして、サービス アカウントの名前と説明を入力します。デフォルトのサービス アカウント ID を使用することも、別の一意の ID を選択することもできます。入力したら、[作成] をクリックします。
  3. 以降の [サービス アカウントの権限(オプション)] セクションは必須ではありません。[続行] をクリックします。
  4. [ユーザーにこのサービス アカウントへのアクセスを許可] 画面で、[キーの作成] セクションまで下にスクロールします。[ キーを作成] をクリックします。
  5. 表示されたサイドパネルで、キーの形式を選択します。JSON をおすすめします。
  6. [作成] をクリックします。新しい公開鍵 / 秘密鍵のペアが生成され、マシンにダウンロードされます。この鍵には他のコピーはありません。安全に保管する方法については、サービス アカウント キーの管理をご覧ください。
  7. [秘密鍵がパソコンに保存されました] ダイアログで [閉じる] をクリックし、[完了] をクリックしてサービス アカウントの表に戻ります。

Google Workspace ドメイン全体の委任を有効にする手順は次のとおりです。

  1. 表から新しく作成されたサービス アカウントを見つけます。[操作] で、、[編集] の順にクリックします。
  2. [サービス アカウントの詳細] で、[ ドメイン全体の委任の表示] をクリックし、[Google Workspace ドメイン全体の委任を有効にする] チェックボックスがオンになっていることを確認します。
  3. まだアプリの OAuth 同意画面を設定していない場合は、ドメイン全体の委任を有効にする前に設定する必要があります。画面の指示に沿って OAuth 同意画面を設定した後、上記の手順を再実行してチェックボックスを再度オンにします。
  4. [保存] をクリックしてサービス アカウントを更新し、サービス アカウントの表に戻ります。 新しい列である [ドメイン全体の委任] が表示されます。[クライアント ID を表示] をクリックし、クライアント ID を確認して書き留めておきます。

ドメイン全体の権限をサービス アカウントに委任する

Google Workspace ドメインのユーザーデータにアクセスするには、作成したサービス アカウントにドメインの特権管理者からアクセス権を付与されている必要があります。ドメイン全体の委任の詳細については、ドメイン全体の委任を使用して Google Workspace API へのアクセスを制御するをご覧ください。

サービス アカウントにドメイン全体の権限を委任する手順は次のとおりです。

  1. Google Workspace ドメインの管理コンソールから、メインメニュー > [セキュリティ] > [API の制御] に移動します。
  2. [ドメイン全体の委任] ペインで、[ドメイン全体の委任を管理] を選択します。
  3. [新しく追加] をクリックします。
  4. [クライアント ID] フィールドに、上記のサービス アカウントの作成手順で取得したクライアント ID を入力します。
  5. [OAuth スコープ] フィールドに、アプリケーションに必要なスコープのカンマ区切りリストを入力します(使用可能なスコープのリストについては、リクエストの承認をご覧ください)。

    たとえば、ドメイン全体のユーザーとグループに対するアクセス権が必要な場合は「https://www.googleapis.com/auth/admin.directory.user, https://www.googleapis.com/auth/admin.directory.group」と入力します。

  6. [承認] をクリックします。

サービス アカウントが、すべてのドメイン ユーザーについて Google Admin SDK Directory API にドメイン全体でアクセスできるようになりました。Google Workspace ドメインのユーザーに代わって、承認済みの Admin SDK Directory サービス オブジェクトをインスタンス化する準備ができました。

Admin SDK Directory サービス オブジェクトをインスタンス化する

次の例では、サービス アカウントのメールアドレスと秘密鍵ファイルを使用します。Java と Python では P12 形式の鍵ファイルを使用しますが、Go では JSON 形式の鍵ファイルを使用します。

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
}

サービス アカウントを使用してリクエストを承認する際にエラーが発生した場合は、JWT エラーコードを確認してください。

次のステップ

Admin SDK Directory API リクエストの承認に問題がなければ、ユーザーの管理と、デベロッパー ガイドで説明されているその他のオペレーションの実行ができます。使用可能な API メソッドの詳細については、API リファレンスをご覧ください。