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

このページでは、クライアント ライブラリを使用して 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>