サービス アカウントとして認証する

このトピックでは、アプリケーションをサービス アカウントとして認証する方法について説明します。一般的な認証シナリオや方法など、Google Cloud APIs への認証に関する一般的な情報については、認証の概要をご覧ください。サービス アカウントの詳細については、Identity and Access Management のドキュメントでサービス アカウントをご覧ください。

認証情報の自動検出

アプリケーションが Google Cloud 環境内で実行されていて、その環境にサービス アカウントが接続されている場合、アプリケーションはそのサービス アカウントの認証情報を取得できます。その後、アプリケーションはこの認証情報を使用して Google Cloud APIs を呼び出すことができます。

Compute Engine、Google Kubernetes Engine、App Engine、Cloud Run、Cloud Functions など、さまざまな Google Cloud サービスのリソースにサービス アカウントを接続できます。これは、認証情報を手動で提供するよりも便利で安全なため、この方法をおすすめします。

また、アプリケーションには Google Cloud クライアント ライブラリを使用することをおすすめします。Google Cloud クライアント ライブラリでは、アプリケーションのデフォルト認証情報(ADC)というライブラリを使用して、サービス アカウントの認証情報を自動的に検索します。サービス アカウントの認証情報は次の順序で検索されます。

  1. 環境変数 GOOGLE_APPLICATION_CREDENTIALS が設定されている場合、ADC では、変数が示すサービス アカウント キーまたは構成ファイルを使用します。

  2. 環境変数 GOOGLE_APPLICATION_CREDENTIALS が設定されていない場合、ADC はコードを実行しているリソースに関連付けられているサービス アカウントを使用します。

    このサービス アカウントは、Compute Engine、Google Kubernetes Engine、App Engine、Cloud Run、Cloud Functions により提供されるデフォルトのサービス アカウントの場合があります。また、作成したユーザー管理のサービス アカウントの場合もあります。

  3. ADC が上に示したいずれの認証情報も使用できない場合は、エラーが発生します。

次のサンプルコードは、アプリケーション コードで ADC ライブラリを使用する方法を示しています。このサンプルを実行するには、Cloud Storage クライアント ライブラリをインストールする必要があります。

C#

public object AuthImplicit(string projectId)
{
    // If you don't specify credentials when constructing the client, the
    // client library will look for credentials in the environment.
    var credential = GoogleCredential.GetApplicationDefault();
    var storage = StorageClient.Create(credential);
    // Make an authenticated API request.
    var buckets = storage.ListBuckets(projectId);
    foreach (var bucket in buckets)
    {
        Console.WriteLine(bucket.Name);
    }
    return null;
}

Go


// implicit uses Application Default Credentials to authenticate.
func implicit() {
	ctx := context.Background()

	// For API packages whose import path is starting with "cloud.google.com/go",
	// such as cloud.google.com/go/storage in this case, if there are no credentials
	// provided, the client library will look for credentials in the environment.
	storageClient, err := storage.NewClient(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer storageClient.Close()

	it := storageClient.Buckets(ctx, "project-id")
	for {
		bucketAttrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(bucketAttrs.Name)
	}

	// For packages whose import path is starting with "google.golang.org/api",
	// such as google.golang.org/api/cloudkms/v1, use NewService to create the client.
	kmsService, err := cloudkms.NewService(ctx)
	if err != nil {
		log.Fatal(err)
	}

	_ = kmsService
}

Java

static void authImplicit() {
  // If you don't specify credentials when constructing the client, the client library will
  // look for credentials via the environment variable GOOGLE_APPLICATION_CREDENTIALS.
  Storage storage = StorageOptions.getDefaultInstance().getService();

  System.out.println("Buckets:");
  Page<Bucket> buckets = storage.list();
  for (Bucket bucket : buckets.iterateAll()) {
    System.out.println(bucket.toString());
  }
}

Node.js

// Imports the Google Cloud client library.
const {Storage} = require('@google-cloud/storage');

// Instantiates a client. If you don't specify credentials when constructing
// the client, the client library will look for credentials in the
// environment.
const storage = new Storage();
// Makes an authenticated API request.
async function listBuckets() {
  try {
    const results = await storage.getBuckets();

    const [buckets] = results;

    console.log('Buckets:');
    buckets.forEach(bucket => {
      console.log(bucket.name);
    });
  } catch (err) {
    console.error('ERROR:', err);
  }
}
listBuckets();

PHP

// Imports the Cloud Storage client library.
use Google\Cloud\Storage\StorageClient;

/**
 * Authenticate to a cloud client library using a service account implicitly.
 *
 * @param string $projectId The Google project ID.
 */
function auth_cloud_implicit($projectId)
{
    $config = [
        'projectId' => $projectId,
    ];

    # If you don't specify credentials when constructing the client, the
    # client library will look for credentials in the environment.
    $storage = new StorageClient($config);

    # Make an authenticated API request (listing storage buckets)
    foreach ($storage->buckets() as $bucket) {
        printf('Bucket: %s' . PHP_EOL, $bucket->name());
    }
}

Python

def implicit():
    from google.cloud import storage

    # If you don't specify credentials when constructing the client, the
    # client library will look for credentials in the environment.
    storage_client = storage.Client()

    # Make an authenticated API request
    buckets = list(storage_client.list_buckets())
    print(buckets)

Ruby

# project_id = "Your Google Cloud project ID"

require "google/cloud/storage"

# If you don't specify credentials when constructing the client, the client
# library will look for credentials in the environment.
storage = Google::Cloud::Storage.new project: project_id

# Make an authenticated API request
storage.buckets.each do |bucket|
  puts bucket.name
end

認証情報を手動で提供する

サービス アカウントが接続されていない環境(オンプレミスや他のクラウド プロバイダなど)でアプリケーションを実行する場合は、Workload Identity 連携を使用する必要があります。

Workload Identity 連携を使用できない場合は、サービス アカウントと 1 つ以上のサービス アカウント キーを作成する必要があります。サービス アカウント キーは、サービス アカウントに関連付けられた認証情報です。作成したサービス アカウント キーをアプリケーションに手動で渡します。

サービス アカウント キーを管理するためのベスト プラクティスを必ず確認してください。

サービス アカウントを作成する

サービス アカウントがない場合は、次の手順で作成します。

Console

サービス アカウントを作成します。

  1. Google Cloud コンソールで [サービス アカウントの作成] ページに移動します。

    [サービス アカウントの作成] に移動
  2. プロジェクトを選択します。
  3. [サービス アカウント名] フィールドに名前を入力します。Google Cloud コンソールでは、この名前に基づいて [サービス アカウント ID] フィールドに値が設定されます。

    [サービス アカウントの説明] フィールドに説明を入力します。例: Service account for quickstart

  4. [作成して続行] をクリックします。
  5. サービス アカウントに Project > Owner ロールを付与します。

    ロールを付与するには、[ロールを選択] リストで [Project > Owner] を選択します。

  6. [続行] をクリックします。
  7. [完了] をクリックして、サービス アカウントの作成を完了します。

    ブラウザ ウィンドウは閉じないでください。次のステップでこれを使用します。

サービス アカウント キーを作成します。

  1. Google Cloud コンソールで、作成したサービス アカウントのメールアドレスをクリックします。
  2. [キー] をクリックします。
  3. [鍵を追加]、[新しい鍵を作成] の順にクリックします。
  4. [作成] をクリックします。JSON キーファイルがパソコンにダウンロードされます。
  5. [閉じる] をクリックします。

gcloud

認証を設定します。

  1. サービス アカウントを作成します。

    gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

    SERVICE_ACCOUNT_NAME をサービス アカウントの名前に置き換えます。

  2. サービス アカウントに roles/owner IAM ロールを付与します。

    gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=roles/owner

    次のように置き換えます。

    • SERVICE_ACCOUNT_NAME: サービス アカウントの名前
    • PROJECT_ID: サービス アカウントを作成したプロジェクト ID
  3. 鍵ファイルを生成します。

    gcloud iam service-accounts keys create FILE_NAME.json --iam-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com

    次のように置き換えます。

    • FILE_NAME: 鍵ファイルの名前
    • SERVICE_ACCOUNT_NAME: サービス アカウントの名前
    • PROJECT_ID: サービス アカウントを作成したプロジェクト ID

環境変数を使用して認証情報を提供する

環境変数 GOOGLE_APPLICATION_CREDENTIALS を設定して、アプリケーション コードに認証情報を指定します。この変数は、現在のシェル セッションにのみ適用されます。この変数を新しいシェル セッションに適用する場合は、シェル起動ファイル(~/.bashrc ファイルや ~/.profile ファイルなど)で変数を設定します。

Linux または macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

KEY_PATH をサービス アカウント キーが含まれる JSON ファイルのパスに置き換えます。

例:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Windows

PowerShell の場合:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

KEY_PATH をサービス アカウント キーが含まれる JSON ファイルのパスに置き換えます。

例:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

コマンド プロンプトの場合:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

KEY_PATH をサービス アカウント キーが含まれる JSON ファイルのパスに置き換えます。

この手順を完了すると、上記のセクションで説明したように、認証情報が自動的に検出されます。必要なコードが少なく、さまざまな環境にコードを移植できるため、ADC の使用をおすすめします。

コードを使用して認証情報を提供する

次の例に示すように、サービス アカウント ファイルを明示的に参照するコードを使用することもできます。以下のサンプルを実行するには、Cloud Storage クライアント ライブラリをインストールする必要があります。

C#

        // Some APIs, like Storage, accept a credential in their Create()
        // method.
        public object AuthExplicit(string projectId, string jsonPath)
        {
            // Explicitly use service account credentials by specifying
            // the private key file.
            var credential = GoogleCredential.FromFile(jsonPath);
            var storage = StorageClient.Create(credential);
            // Make an authenticated API request.
            var buckets = storage.ListBuckets(projectId);
            foreach (var bucket in buckets)
            {
                Console.WriteLine(bucket.Name);
            }
            return null;
        }
        // Other APIs, like Language, accept a channel in their Create()
        // method.
        public object AuthExplicit(string projectId, string jsonPath)
        {
            LanguageServiceClientBuilder builder = new LanguageServiceClientBuilder
            {
                CredentialsPath = jsonPath
            };

            LanguageServiceClient client = builder.Build();
            AnalyzeSentiment(client);
            return 0;
        }

Go


// explicit reads credentials from the specified path.
func explicit(jsonPath, projectID string) {
	ctx := context.Background()
	client, err := storage.NewClient(ctx, option.WithCredentialsFile(jsonPath))
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()
	fmt.Println("Buckets:")
	it := client.Buckets(ctx, projectID)
	for {
		battrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(battrs.Name)
	}
}

Java

static void authExplicit(String jsonPath) throws IOException {
  // You can specify a credential file by providing a path to GoogleCredentials.
  // Otherwise credentials are read from the GOOGLE_APPLICATION_CREDENTIALS environment variable.
  GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath))
        .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
  Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();

  System.out.println("Buckets:");
  Page<Bucket> buckets = storage.list();
  for (Bucket bucket : buckets.iterateAll()) {
    System.out.println(bucket.toString());
  }
}

Node.js

// Imports the Google Cloud client library.
const {Storage} = require('@google-cloud/storage');

// Instantiates a client. Explicitly use service account credentials by
// specifying the private key file. All clients in google-cloud-node have this
// helper, see https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/docs/authentication.md
// const projectId = 'project-id'
// const keyFilename = '/path/to/keyfile.json'
const storage = new Storage({projectId, keyFilename});

// Makes an authenticated API request.
async function listBuckets() {
  try {
    const [buckets] = await storage.getBuckets();

    console.log('Buckets:');
    buckets.forEach(bucket => {
      console.log(bucket.name);
    });
  } catch (err) {
    console.error('ERROR:', err);
  }
}
listBuckets();

PHP

namespace Google\Cloud\Samples\Auth;

// Imports the Cloud Storage client library.
use Google\Cloud\Storage\StorageClient;

/**
 * Authenticate to a cloud client library using a service account explicitly.
 *
 * @param string $projectId           The Google project ID.
 * @param string $serviceAccountPath  Path to service account credentials JSON.
 */
function auth_cloud_explicit($projectId, $serviceAccountPath)
{
    # Explicitly use service account credentials by specifying the private key
    # file.
    $config = [
        'keyFilePath' => $serviceAccountPath,
        'projectId' => $projectId,
    ];
    $storage = new StorageClient($config);

    # Make an authenticated API request (listing storage buckets)
    foreach ($storage->buckets() as $bucket) {
        printf('Bucket: %s' . PHP_EOL, $bucket->name());
    }
}

Python

def explicit():
    from google.cloud import storage

    # Explicitly use service account credentials by specifying the private key
    # file.
    storage_client = storage.Client.from_service_account_json(
        'service_account.json')

    # Make an authenticated API request
    buckets = list(storage_client.list_buckets())
    print(buckets)

Ruby

# project_id = "Your Google Cloud project ID"
# key_file   = "path/to/service-account.json"
require "google/cloud/storage"

# Explicitly use service account credentials by specifying the private key
# file.
storage = Google::Cloud::Storage.new project: project_id, keyfile: key_file

# Make an authenticated API request
storage.buckets.each do |bucket|
  puts bucket.name
end

API エラーのトラブルシューティング

API リクエストが失敗した場合のトラブルシューティング方法について詳しくは、Cloud APIs のエラーをご覧ください。

次のステップ

使ってみる

Google Cloud を初めて使用する場合は、アカウントを作成して、実際のシナリオでの Google プロダクトのパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。

無料で開始