クライアント ライブラリを使用して認証する

このページでは、クライアント ライブラリを使用して Google API にアクセスする方法について説明します。

クライアント ライブラリを使用すると、サポートされている言語を使用して Google Cloud API に簡単にアクセスできます。 Google Cloud API は、サーバーにリクエストを送信して直接利用することもできますが、クライアント ライブラリを使用すると、記述するコードの量を大幅に削減できます。クライアント ライブラリでは、アプリケーションのデフォルト認証情報(ADC)をサポートしているため、この方法は認証処理で非常に効果的です。

外部ソース(お客様など)からの認証情報の構成(JSON、ファイル、ストリーム)を受け入れる場合、外部ソースからの認証情報の構成を使用する際のセキュリティ要件を確認してください。

クライアント ライブラリでアプリケーションのデフォルト認証情報を使用する

アプリケーションのデフォルト認証情報を使用してアプリケーションの認証を行うには、まず、アプリケーションが実行されている環境に対して ADC を設定する必要があります。クライアント ライブラリを使用してクライアントを作成すると、クライアント ライブラリは、ADC に指定した認証情報を自動的にチェックし、コードで使用する API の認証に使用します。アプリケーションでトークンを明示的に認証または管理する必要はありません。これらの要件は認証ライブラリによって自動的に管理されます。

ローカル開発環境では、gcloud CLI でユーザー認証情報またはサービス アカウントの権限借用を使用して ADC を設定できます。本番環境では、サービス アカウントを接続して ADC を設定します。

クライアントの作成例

次のコードサンプルでは、Cloud Storage サービスのクライアントを作成します。実際のコードではさまざまなクライアントが必要になりますが、ここでは、認証を明示的に行わずに使用できるクライアントの作成を目的としているため、このようなコードサンプルになっています。

次のサンプルを実行する前に、次の手順を完了する必要があります。

Go

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/storage"
	"google.golang.org/api/iterator"
)

// authenticateImplicitWithAdc uses Application Default Credentials
// to automatically find credentials and authenticate.
func authenticateImplicitWithAdc(w io.Writer, projectId string) error {
	// projectId := "your_project_id"

	ctx := context.Background()

	// NOTE: Replace the client created below with the client required for your application.
	// Note that the credentials are not specified when constructing the client.
	// The client library finds your credentials using ADC.
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	it := client.Buckets(ctx, projectId)
	for {
		bucketAttrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "Bucket: %v\n", bucketAttrs.Name)
	}

	fmt.Fprintf(w, "Listed all storage buckets.\n")

	return nil
}

Java


import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.io.IOException;

public class AuthenticateImplicitWithAdc {

  public static void main(String[] args) throws IOException {
    // TODO(Developer):
    //  1. Before running this sample,
    //  set up Application Default Credentials as described in
    //  https://cloud.google.com/docs/authentication/external/set-up-adc
    //  2. Replace the project variable below.
    //  3. Make sure you have the necessary permission to list storage buckets
    //  "storage.buckets.list"
    String projectId = "your-google-cloud-project-id";
    authenticateImplicitWithAdc(projectId);
  }

  // When interacting with Google Cloud Client libraries, the library can auto-detect the
  // credentials to use.
  public static void authenticateImplicitWithAdc(String project) throws IOException {

    // *NOTE*: Replace the client created below with the client required for your application.
    // Note that the credentials are not specified when constructing the client.
    // Hence, the client library will look for credentials using ADC.
    //
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    Storage storage = StorageOptions.newBuilder().setProjectId(project).build().getService();

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

Node.js

/**
 * TODO(developer):
 *  1. Uncomment and replace these variables before running the sample.
 *  2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
 *  3. Make sure you have the necessary permission to list storage buckets "storage.buckets.list"
 *    (https://cloud.google.com/storage/docs/access-control/iam-permissions#bucket_permissions)
 */
// const projectId = 'YOUR_PROJECT_ID';

const {Storage} = require('@google-cloud/storage');

async function authenticateImplicitWithAdc() {
  // This snippet demonstrates how to list buckets.
  // NOTE: Replace the client created below with the client required for your application.
  // Note that the credentials are not specified when constructing the client.
  // The client library finds your credentials using ADC.
  const storage = new Storage({
    projectId,
  });
  const [buckets] = await storage.getBuckets();
  console.log('Buckets:');

  for (const bucket of buckets) {
    console.log(`- ${bucket.name}`);
  }

  console.log('Listed all storage buckets.');
}

authenticateImplicitWithAdc();

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


from google.cloud import storage


def authenticate_implicit_with_adc(project_id="your-google-cloud-project-id"):
    """
    When interacting with Google Cloud Client libraries, the library can auto-detect the
    credentials to use.

    // TODO(Developer):
    //  1. Before running this sample,
    //  set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    //  2. Replace the project variable.
    //  3. Make sure that the user account or service account that you are using
    //  has the required permissions. For this sample, you must have "storage.buckets.list".
    Args:
        project_id: The project id of your Google Cloud project.
    """

    # This snippet demonstrates how to list buckets.
    # *NOTE*: Replace the client created below with the client required for your application.
    # Note that the credentials are not specified when constructing the client.
    # Hence, the client library will look for credentials using ADC.
    storage_client = storage.Client(project=project_id)
    buckets = storage_client.list_buckets()
    print("Buckets:")
    for bucket in buckets:
        print(bucket.name)
    print("Listed all storage buckets.")

Ruby

def authenticate_implicit_with_adc project_id:
  # The ID of your Google Cloud project
  # project_id = "your-google-cloud-project-id"

  ###
  # When interacting with Google Cloud Client libraries, the library can auto-detect the
  # credentials to use.
  # TODO(Developer):
  #   1. Before running this sample,
  #      set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
  #   2. Replace the project variable.
  #   3. Make sure that the user account or service account that you are using
  #      has the required permissions. For this sample, you must have "storage.buckets.list".
  ###

  require "google/cloud/storage"

  # This sample demonstrates how to list buckets.
  # *NOTE*: Replace the client created below with the client required for your application.
  # Note that the credentials are not specified when constructing the client.
  # Hence, the client library will look for credentials using ADC.
  storage = Google::Cloud::Storage.new project_id: project_id
  buckets = storage.buckets
  puts "Buckets: "
  buckets.each do |bucket|
    puts bucket.name
  end
  puts "Plaintext: Listed all storage buckets."
end

クライアント ライブラリで API キーを使用する

API キーは、API キーを受け取る API のクライアント ライブラリでのみ使用できます。また、API キーに、API での使用を妨げる API 制限が設定されていない必要があります。

エクスプレス モードで作成された API キーの詳細については、Google Cloud エクスプレス モードのよくある質問をご覧ください。

この例では、API キーを受け入れることができる Cloud Natural Language API を使用し、ライブラリに API キーを提供する方法を示します。

C#

このサンプルを実行するには、Natural Language クライアント ライブラリをインストールする必要があります。


using Google.Cloud.Language.V1 class="devsite-xref-link" href="https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Language.V1/latest/Google.Cloud.Language.V1.ClassificationModelOptions.Types.V2Model.Types.ContentCategoriesVersion.html#Google_Cloud_Language_V1_ClassificationM"odelOptions_T"ypes_V2Model_Types_ContentCategoriesVersion_V1" track-type="exampleCode" track-name="xrefLink" track-metadata-lang="DOTNET" track"-metadata-mo"difier="Google.Cloud.Language.V1" track-metadata-href="https://cloud.google.com/dotnet/d"ocs/reference/Google.Cloud.Language.V1/latest/Googl"e.Cloud.Language.V1.Classific"ationModelOptions.Types.V2Model.Types.Conten"tCategoriesVersion.html#Google_Cloud_Language_V1_ClassificationModelOptions_Types_V2Model_Types_ContentCategoriesVersion_V1">V1;
using System;

public class UseApiKeySample
{
    public void AnalyzeSentiment(string apiKey)
    {
        LanguageServiceClient client = new LanguageServiceClientBuilder
        {
            ApiKey = apiKey
        }.Build();

        string text = Hello, world!;

        AnalyzeSentimentResponse response = client.AnalyzeSentiment(Document.FromPlainText(text));
        Console.WriteLine($Text: {text});
        Sentiment sentiment = response.DocumentSentiment;
        Console.WriteLine($Sentiment: {sentiment.Score}, {sentiment.Magnitude});
        Console.WriteLine(Successfully authenticated using the API key);
    }
}

C++

このサンプルを実行するには、Natural Language クライアント ライブラリをインストールする必要があります。

#include "google/cloud/language/v1/language_client.h"
#include "google/cloud/credentials.h"
#include "google/cloud/options.h"

void AuthenticateWithApiKey(std::vector<std::string> const& argv) {
  if (argv.size() != 2) {
    throw google::cloud::testing_util::Usage{
        "authenticate-with-api-key <project-id> <api-key>"};
  }
  namespace gc = ::google::cloud;
  auto options = gc::Options{}.set<gc::UnifiedCredentialsOption>(
      gc::MakeApiKeyCredentials(argv[1]));
  auto client = gc::language_v1::LanguageServiceClient(
      gc::language_v1::MakeLanguageServiceConnection(options));

  auto constexpr kText = "Hello, world!";

  google::cloud::language::v1::Document d;
  d.set_content(kText);
  d.set_type(google::cloud::language::v1::Document::PLAIN_TEXT);

  auto response = client.AnalyzeSentiment(d, {});
  if (!response) throw std::move(response.status());
  auto const& sentiment = response->document_sentiment();
  std::cout << "Text: " << kText << "\n";
  std::cout << "Sentiment: " << sentiment.score() << ", "
            << sentiment.magnitude() << "\n";
  std::cout << "Successfully authenticated using the API key\n";
}

Go

このサンプルを実行するには、Natural Language クライアント ライブラリをインストールする必要があります。

import (
	"context"
	"fmt"
	"io"

	language "cloud.google.com/go/language/apiv1"
	"cloud.google.com/go/language/apiv1/languagepb"
	"google.golang.org/api/option"
)

// authenticateWithAPIKey authenticates with an API key for Google Language
// service.
func authenticateWithAPIKey(w io.Writer, apiKey string) error {
	// apiKey := "api-key-string"

	ctx := context.Background()

	// Initialize the Language Service client and set the API key.
	client, err := language.NewClient(ctx, option.WithAPIKey(apiKey))
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	text := "Hello, world!"
	// Make a request to analyze the sentiment of the text.
	res, err := client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_Content{
				Content: text,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
	})
	if err != nil {
		return fmt.Errorf("AnalyzeSentiment: %w", err)
	}

	fmt.Fprintf(w, "Text: %s\n", text)
	fmt.Fprintf(w, "Sentiment score: %v\n", res.DocumentSentiment.Score)
	fmt.Fprintln(w, "Successfully authenticated using the API key.")

	return nil
}

Node.js

このサンプルを実行するには、Natural Language クライアント ライブラリをインストールする必要があります。


const {
  v1: {LanguageServiceClient},
} = require('@google-cloud/language');

/**
 * Authenticates with an API key for Google Language service.
 *
 * @param {string} apiKey An API Key to use
 */
async function authenticateWithAPIKey(apiKey) {
  const language = new LanguageServiceClient({apiKey});

  // Alternatively:
  // const {GoogleAuth} = require('google-auth-library');
  // const auth = new GoogleAuth({apiKey});
  // const language = new LanguageServiceClient({auth});

  const text = 'Hello, world!';

  const [response] = await language.analyzeSentiment({
    document: {
      content: text,
      type: 'PLAIN_TEXT',
    },
  });

  console.log(`Text: ${text}`);
  console.log(
    `Sentiment: ${response.documentSentiment.score}, ${response.documentSentiment.magnitude}`
  );
  console.log('Successfully authenticated using the API key');
}

authenticateWithAPIKey();

Python

このサンプルを実行するには、Natural Language クライアント ライブラリをインストールする必要があります。


from google.cloud import language_v1


def authenticate_with_api_key(api_key_string: str) -> None:
    """
    Authenticates with an API key for Google Language service.

    TODO(Developer): Replace this variable before running the sample.

    Args:
        api_key_string: The API key to authenticate to the service.
    """

    # Initialize the Language Service client and set the API key
    client = language_v1.LanguageServiceClient(
        client_options={"api_key": api_key_string}
    )

    text = "Hello, world!"
    document = language_v1.Document(
        content=text, type_=language_v1.Document.Type.PLAIN_TEXT
    )

    # Make a request to analyze the sentiment of the text.
    sentiment = client.analyze_sentiment(
        request={"document": document}
    ).document_sentiment

    print(f"Text: {text}")
    print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
    print("Successfully authenticated using the API key")

アプリケーションで API キーを使用する場合は、保存時と転送時の両方でキーの安全確保に努めてください。API キーが公開されると、アカウントに対して予想外の料金が課される可能性があります。詳細については、API キーの管理に関するベスト プラクティスをご覧ください。

外部ソースの認証情報構成を使用する場合のセキュリティ要件

通常、認証情報の構成は、gcloud CLI コマンドまたは Google Cloud コンソールを使用して生成します。たとえば、gcloud CLI を使用してローカル ADC ファイルまたはログイン構成ファイルを生成できます。同様に、Google Cloud コンソールを使用してサービス アカウント キーを作成してダウンロードすることもできます。

ただし、一部のユースケースでは、認証情報の構成が外部エンティティから提供されます。これらの認証情報の構成は、Google API の認証に使用することを目的としています。

認証情報の構成には、認証ライブラリがトークンの取得に使用するエンドポイントとファイルパスが含まれる場合があります。外部ソースから認証情報の構成を受け入れる場合、使用前に構成を検証する必要があります。構成を検証しないと、悪意のある攻撃者が認証情報を使用してシステムとデータを侵害する可能性があります。

外部ソースの認証情報の構成を検証する

外部認証情報を検証する方法は、アプリケーションが受け入れる認証情報の種類によって異なります。

サービス アカウント キーを検証する

アプリケーションがサービス アカウント キーのみを受け入れる場合、次の例に示すように、サービス アカウント キーに固有の認証情報ローダを使用します。タイプ固有の認証情報ローダは、サービス アカウント キーに存在するフィールドのみを解析します。これにより、脆弱性が公開されることはありません。

C#

var saCredential = ServiceAccountCredential.FromServiceAccountData(stream);

C++

auto cred = google::cloud::MakeServiceAccountCredentials(json)

Java

ServiceAccountCredentials credentials =
      ServiceAccountCredentials.fromJson(json, new HttpTransportFactory());

Node.js

const keys = JSON.parse(json_input)
const authClient = JWT.fromJSON(keys);

PHP

cred = new Google\Auth\Credentials\ServiceAccountCredentials($scope, $jsonKey);

Python

cred = service_account.Credentials.from_service_account_info(json_data)

Ruby

creds = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: json_stream)

タイプ固有の認証情報ローダを使用できない場合は、type フィールドの値が service_account であることを確認して認証情報を検証します。type フィールドの値が他の値の場合は、サービス アカウント キーを使用しないでください。

他の認証情報の構成を検証する

アプリケーションがサービス アカウント キー以外の任意の種類の認証情報を受け入れる場合は、追加の検証を行う必要があります。他のタイプの認証情報構成の例には、ADC 認証情報ファイルWorkload Identity 連携認証情報ファイルWorkforce Identity 連携ログイン構成ファイルなどがあります。

次の表に、認証情報に存在する場合に検証が必要なフィールドを示します。これらのフィールドは、すべての認証情報の構成に存在するわけではありません。

フィールド 目的 期待される価値
service_account_impersonation_url 認証ライブラリは、このフィールドを使用してエンドポイントにアクセスし、権限借用されるサービス アカウントのアクセス トークンを生成します。 https://iamcredentials.googleapis.com.com/v1/projects/-/serviceAccounts/service account email:generateAccessToken
token_url 認証ライブラリは、外部トークンをこのエンドポイントに送信して、連携アクセス トークンと交換します。 https://sts.googleapis.com.com/v1/token
credential_source.file 認証ライブラリは、このフィールドで指定された場所にあるファイルから外部トークンを読み取り、token_url エンドポイントに送信します。 外部トークンを含むファイルのパス。このパスは認識できるはずです。
credential_source.url 外部トークンを返すエンドポイント。認証ライブラリは、この URL にリクエストを送信し、token_url エンドポイントにレスポンスを送信します。

次のいずれかの項目:

  • クラウド プロバイダが提供する既知のエンドポイント。
  • トークンを提供するように明示的に設定したエンドポイント。
credential_source.executable.command GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES 環境変数が 1 に設定されている場合、認証ライブラリはこのコマンドまたは実行可能ファイルを実行します。 外部トークンを返す実行可能ファイルまたはコマンド。このコマンドを認識し、安全であることを確認する必要があります。
credential_source.aws.url 認証ライブラリは、この URL にリクエストを発行して AWS セキュリティ トークンを取得します。

次のいずれかの正確な値:

  • http://169.254.169.254/latest/meta-data/iam/security-credentials
  • http://[fd00:ec2::254]/latest/meta-data/iam/security-credentials
credential_source.aws.region_url 認証ライブラリは、この URL にリクエストを発行して、アクティブな AWS リージョンを取得します。

次のいずれかの正確な値:

  • http://169.254.169.254/latest/meta-data/placement/availability-zone
  • http://[fd00:ec2::254]/latest/meta-data/placement/availability-zone
credential_source.aws.imdsv2_session_token_url 認証ライブラリは、この URL にリクエストを発行して AWS セッション トークンを取得します。

次のいずれかの正確な値:

  • http://169.254.169.254/latest/api/token
  • http://[fd00:ec2::254]/latest/api/token

次のステップ