API キーを使用して認証する

このページでは、API キーを使用して、API キーをサポートする Google Cloud APIs およびサービスに対する認証を行う方法について説明します。

ほとんどの Google Cloud APIs は API キーをサポートしていません。この認証方法を使用する前に、使用する API が API キーをサポートしていることを確認してください。

API キーを使用して Google Maps Platform の認証を行う方法については、Google Maps Platform のドキュメントをご覧ください。API Keys API の詳細については、API Keys API のドキュメントをご覧ください。

API キーの概要

API キーを使用して API を認証する場合、API キーはプリンシパルを識別しません。また、認可情報も提供しません。したがって、リクエストされた操作を実行する権限が呼び出し元にあるかどうかを Identity and Access Management(IAM)へのリクエストにより確認することはありません。

API キーは、課金と割り当てのために、リクエストを Google Cloud プロジェクトに関連付けます。API キーは呼び出し元を特定しないため、一般公開のデータやリソースへアクセスする際によく使用されます。

多くの Google Cloud APIs では、認証に API キーを使用できません。使用するサービスまたは API の認証ドキュメントで、API キーに対応しているかどうかを確認してください。

API キーには次のコンポーネントがあり、キーの管理と使用に使用します。

文字列
API キー文字列は暗号化された文字列です(例: AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe)。API キーを使用して認証する場合は、常にキーの文字列を使用します。API キーには、関連付けられた JSON ファイルがありません。
ID
API キー ID は、Google Cloud 管理ツールでキーを一意に識別するために使用されます。キー ID を使用して認証することはできません。キー ID は、Google Cloud コンソールのキー編集ページの URL で確認できます。Google Cloud CLI を使用してプロジェクトのキーを一覧表示することで、キー ID を取得することもできます。
表示名
表示名は、キーを作成または更新するときに設定できるオプションのわかりやすい名前です。

API キーを管理するには、そのプロジェクトで API キー管理者のロール(roles/serviceusage.apiKeysAdmin)が必要です。

始める前に

このページのサンプルをどのように使うかに応じて、タブを選択してください。

コンソール

Google Cloud コンソールを使用して Google Cloud サービスと API にアクセスする場合、認証を設定する必要はありません。

gcloud

このページの gcloud CLI のサンプルは、次のいずれかの開発環境から使用できます。

  • Cloud Shell: gcloud CLI がすでに設定されているオンライン ターミナルを使用するには、Cloud Shell をアクティブにします。

    このページの下部で Cloud Shell セッションが開始し、コマンドライン プロンプトが表示されます。セッションが初期化されるまで数秒かかることがあります。

  • ローカルシェル: ローカル開発環境で gcloud CLI を使用するには、gcloud CLI をインストールして初期化してください。

Java

このページの Java サンプルをローカル開発環境から使用するには、gcloud CLI をインストールして初期化し、自身のユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定してください。

  1. Google Cloud CLI をインストールします。
  2. gcloud CLI を初期化するには:

    gcloud init
  3. Google アカウントのローカル認証情報を作成します。

    gcloud auth application-default login

詳細については、Google Cloud の認証に関するドキュメントのローカル開発環境の認証の設定をご覧ください。

Python

このページの Python サンプルをローカル開発環境から使用するには、gcloud CLI をインストールして初期化し、自身のユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定してください。

  1. Google Cloud CLI をインストールします。
  2. gcloud CLI を初期化するには:

    gcloud init
  3. Google アカウントのローカル認証情報を作成します。

    gcloud auth application-default login

詳細については、Google Cloud の認証に関するドキュメントのローカル開発環境の認証の設定をご覧ください。

REST

このページの REST API サンプルをローカル開発環境で使用するには、gcloud CLI に指定した認証情報を使用します。

    Google Cloud CLI をインストールし、次のコマンドを実行して初期化します。

    gcloud init

API キーを作成する

API キーを作成するには、次のいずれかのオプションを使用します。

コンソール

  1. Google Cloud コンソールで、[認証情報] ページに移動します。

    [認証情報] に移動

  2. [認証情報の作成] を選択し、メニューから [API キー] を選択します。

    [API キーを作成しました] ダイアログに、新しく作成されたキーの文字列が表示されます。

gcloud

API キーを作成するには、gcloud beta services api-keys create コマンドを使用します。

DISPLAY_NAME は、わかりやすいキー名に置き換えます。

 gcloud beta services api-keys create --display-name=DISPLAY_NAME
 

Java

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


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.ApiTarget;
import com.google.api.apikeys.v2.CreateKeyRequest;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.LocationName;
import com.google.api.apikeys.v2.Restrictions;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateApiKey {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    //  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 create API keys.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    createApiKey(projectId);
  }

  // Creates an API key.
  public static void createApiKey(String projectId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      Key key = Key.newBuilder()
          .setDisplayName("My first API key")
          // Set the API key restriction.
          // You can also set browser/ server/ android/ ios based restrictions.
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys#api_key_restrictions
          .setRestrictions(Restrictions.newBuilder()
              // Restrict the API key usage by specifying the target service and methods.
              // The API key can only be used to authenticate the specified methods in the service.
              .addApiTargets(ApiTarget.newBuilder()
                  .setService("translate.googleapis.com")
                  .addMethods("translate.googleapis.com.TranslateText")
                  .build())
              .build())
          .build();

      // Initialize request and set arguments.
      CreateKeyRequest createKeyRequest = CreateKeyRequest.newBuilder()
          // API keys can only be global.
          .setParent(LocationName.of(projectId, "global").toString())
          .setKey(key)
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.createKeyAsync(createKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      // To restrict the usage of this API key, use the value in "result.getName()".
      System.out.printf("Successfully created an API key: %s", result.getName());
    }
  }
}

Python

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


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key

def create_api_key(project_id: str, suffix: str) -> Key:
    """
    Creates and restrict an API key. Add the suffix for uniqueness.

    TODO(Developer):
    1. Before running this sample,
      set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    2. Make sure you have the necessary permission to create API keys.

    Args:
        project_id: Google Cloud project id.

    Returns:
        response: Returns the created API Key.
    """
    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    key = api_keys_v2.Key()
    key.display_name = f"My first API key - {suffix}"

    # Initialize request and set arguments.
    request = api_keys_v2.CreateKeyRequest()
    request.parent = f"projects/{project_id}/locations/global"
    request.key = key

    # Make the request and wait for the operation to complete.
    response = client.create_key(request=request).result()

    print(f"Successfully created an API key: {response.name}")
    # For authenticating with the API key, use the value in "response.key_string".
    # To restrict the usage of this API key, use the value in "response.name".
    return response

REST

API キーを作成するには、keys.create メソッドを使用します。このリクエストは、長時間実行オペレーションを返します。新しいキーの情報を取得するには、オペレーションをポーリングする必要があります。

次の値を置き換えます。

  • DISPLAY_NAME: 省略可。キーのわかりやすい名前。
  • PROJECT_ID: Google Cloud プロジェクト ID または名前。
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d {'"displayName" : "DISPLAY_NAME"'} \
"https://apikeys./v2/projects/PROJECT/locations/global/keys"

REST API を使用した API キーの作成の詳細については、API Keys API ドキュメントの API キーの作成をご覧ください。

キー文字列をコピーして安全に保管します。後で削除する予定のテストキーを使用している場合を除き、アプリケーションと API キーの制限を追加してください。

API キーを使用する

API が API キーの使用をサポートしている場合は、API キーを使用して API を認証できます。REST リクエストと、それをサポートするクライアント ライブラリで、API キーを使用します。

REST で API キーを使用する

API キーは、次の形式のクエリ パラメータとして REST API 呼び出しに渡すことができます。API_KEY は、API キーのキー文字列に置き換えます。

API キーを保護する

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

  • キーに API キー制限を追加します。

    制限を追加することで、API キーの使用方法を制限し、API キーが不正使用された場合の影響を軽減できます。

  • 不要な API キーを削除して、攻撃を受けるリスクを最小限に抑えます。

  • API キーを定期的に再作成します。

    新しい API キーを定期的に作成し、古いキーを削除して、新しい API キーを使用するようにアプリケーションを更新します。

API キーの制限を適用する

API キーは、デフォルトでは制限されません。制限されていないキーは、誰でもどこからでも使用できるため安全ではありません。本番環境アプリケーションの場合は、アプリケーションの制限API の制限の両方を設定する必要があります。

アプリケーションの制限を追加する

アプリケーションの制限では、API キーの使用を許可するウェブサイト、IP アドレス、またはアプリを指定します。

一度に適用できるアプリケーションの制限は 1 種類のみです。アプリケーションのニーズに合わせて、制限のタイプを選択します。

オプション アプリケーションの種類 メモ
HTTP リファラー ウェブ アプリケーション このキーを使用できるウェブサイトを指定します。
IP アドレス 特定のサーバーによって呼び出されるアプリケーション キーを使用できるサーバーまたは cron ジョブを指定します。
Android アプリ Android アプリ キーを使用できる Android アプリを指定します。
iOS アプリ iOS アプリ キーを使用できる iOS バンドルを指定します。

HTTP リファラー

API キーを使用できるウェブサイトを制限するには、HTTP リファラーの制限を 1 つ以上追加します。

サブドメインまたはパスにはワイルドカード文字(*)を使用できますが、URL の途中にワイルドカード文字を挿入することはできません。たとえば、*.google.com は有効で、.google.com で終わるすべてのサイトを受け入れます。しかし、mysubdomain*.google.com は有効な制限ではありません。

HTTP リファラーの制限にはポート番号を含めることができます。ポート番号を含めると、そのポートを使用するリクエストのみが照合されます。ポート番号を指定しない場合、任意のポート番号からのリクエストが照合されます。

API キーには、最大 1,200 件の HTTP リファラーを追加できます。

次の表に、シナリオとブラウザの制限の例を示します。

シナリオ 制限事項
特定の URL を許可する 正確なパスの URL を追加してください。例:
www.example.com/path
www.example.com/path/path

一部のブラウザでは、クロスオリジン リクエストのオリジン URL のみを送信するリファラー ポリシーが実装されています。これらのブラウザのユーザーは、ページ限定 URL の制限が設定されたキーを使用できません。

サイトの任意の URL を許可する allowedReferers リストに 2 つの URL を設定する必要があります。
  1. サブドメインを付けないドメインの URL、およびパスのワイルドカードを含む URL。例:
    example.com/*
  2. サブドメインのワイルドカードとパスのワイルドカードを含む 2 つ目の URL。例:
    *.example.com/*
1 つのサブドメインまたはネイキッド ドメイン内の任意の URL を許可する

ドメイン全体を許可するには、allowedReferers リストに 2 つの URL を設定する必要があります。

  1. 末尾にスラッシュを付けないドメインの URL。例:
    www.example.com
    sub.example.com
    example.com
  2. パスにワイルドカードを含めた、ドメインの 2 つ目の URL。例:
    www.example.com/*
    sub.example.com/*
    example.com/*

API キーを特定のウェブサイトに制限するには、次のいずれかのオプションを使用します。

コンソール

  1. Google Cloud コンソールで、[認証情報] ページに移動します。

    [認証情報] に移動

  2. 制限する API キーの名前をクリックします。

  3. [アプリケーションの制限] で [HTTP リファラー] を選択します。

  4. 追加する制限ごとに、[項目を追加] をクリックし、制限を入力して、[完了] をクリックします。

  5. [保存] をクリックして変更を保存し、API キーリストに戻ります。

gcloud

  1. 制限するキーの ID を取得します。

    ID は表示名やキー文字列とは異なります。ID を取得するには、gcloud services api-keys list コマンドを使用して、プロジェクト内のキーを一覧表示します。

  2. API キーに HTTP リファラーの制限を追加するには、gcloud beta services api-keys update コマンドを使用します。

    次の値を置き換えます。

    • KEY_ID: 制限するキーの ID。
    • ALLOWED_REFERRER_1: HTTP リファラーの制限。

      必要に応じて制限を追加できます。制限はカンマで区切ります。更新コマンドでは、すべてのリファラーの制限を指定する必要があります。指定したリファラー制限により、キー上の任意の既存のリファラー制限が置き換えられます。

    gcloud beta services api-keys update KEY_ID \
     --allowed-referrers="ALLOWED_REFERRER_1"
    

Java

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


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.BrowserKeyRestrictions;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyHttp {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyHttp(projectId, keyId);
  }

  // Restricts an API key. To restrict the websites that can use your API key,
  // you add one or more HTTP referrer restrictions.
  public static void restrictApiKeyHttp(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage to specific websites by adding them
      // to the list of allowed_referrers.
      Restrictions restrictions = Restrictions.newBuilder()
          .setBrowserKeyRestrictions(BrowserKeyRestrictions.newBuilder()
              .addAllowedReferrers("www.example.com/*")
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

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


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key

def restrict_api_key_http(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key. To restrict the websites that can use your API key,
    you add one or more HTTP referrer restrictions.

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

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage to specific websites by adding them to the list of allowed_referrers.
    browser_key_restrictions = api_keys_v2.BrowserKeyRestrictions()
    browser_key_restrictions.allowed_referrers = ["www.example.com/*"]

    # Set the API restriction.
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.browser_key_restrictions = browser_key_restrictions

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 制限するキーの ID を取得します。

    ID は表示名やキー文字列とは異なります。ID を取得するには、keys.list メソッドを使用します。ID はレスポンスの uid フィールドに示されます。

    PROJECT_ID は、Google Cloud プロジェクト ID または名前に置き換えます。

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys./v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. API キーに HTTP リファラーの制限を追加するには、keys.patch メソッドを使用します。

    このリクエストは、長時間実行オペレーションを返します。オペレーションをポーリングして、オペレーションが完了したタイミングを把握し、オペレーションのステータスを取得する必要があります。

    次の値を置き換えます。

    • ALLOWED_REFERRER_1: HTTP リファラーの制限。

      必要に応じて制限を追加できます。制限はカンマで区切ります。すべてのリファラー制限にリクエストを指定する必要があります。指定したリファラー制限により、キー上の任意の既存のリファラー制限が置き換えられます。

    • PROJECT_ID: Google Cloud プロジェクト ID または名前。

    • KEY_ID: 制限するキーの ID。

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "browserKeyRestrictions": {
      "allowedReferrers": ["ALLOWED_REFERRER_1"]
    }
    }
    }' \
    "https://apikeys./v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

REST API を使用してキーに HTTP リファラー制限を追加する方法については、API Keys API ドキュメントのブラウザ制限の追加をご覧ください。

IP アドレス

API キーの使用が許可されている呼び出し元(ウェブサーバーや cron ジョブなど)の IP アドレスを 1 つ以上指定できます。IP アドレスは、次のいずれかの形式で指定できます。

  • IPv4(198.51.100.1
  • IPv6(2001:db8::1
  • CIDR 表記を使用したサブネット(198.51.100.0/242001:db8::/64

localhost の使用は、サーバーの制限ではサポートされていません。

API キーを特定の IP アドレスに制限するには、次のいずれかのオプションを使用します。

コンソール

  1. Google Cloud コンソールで、[認証情報] ページに移動します。

    [認証情報] に移動

  2. 制限する API キーの名前をクリックします。

  3. [アプリケーションの制限] で [IP アドレス] を選択します。

  4. 追加する IP アドレスごとに [項目を追加] をクリックし、アドレスを入力して [完了] をクリックします。

  5. [保存] をクリックして変更を保存し、API キーリストに戻ります。

gcloud

  1. 制限するキーの ID を取得します。

    ID は表示名やキー文字列とは異なります。ID を取得するには、gcloud services api-keys list コマンドを使用して、プロジェクト内のキーを一覧表示します。

  2. gcloud beta services api-keys update コマンドを使用して、サーバー(IP アドレス)の制限を API キーに追加します。

    次の値を置き換えます。

    • KEY_ID: 制限するキーの ID。
    • ALLOWED_IP_ADDR_1: 許可する IP アドレス。

      IP アドレスは必要な数だけ追加できます。複数のアドレスを入力する場合は、カンマで区切ります。

    gcloud beta services api-keys update KEY_ID \
    --allowed-ips="ALLOWED_IP_ADDR_1"
    

Java

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


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.ServerKeyRestrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyServer {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyServer(projectId, keyId);
  }

  // Restricts the API key based on IP addresses. You can specify one or more IP addresses
  // of the callers, for example web servers or cron jobs, that are allowed to use your API key.
  public static void restrictApiKeyServer(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the IP addresses.
      // You can specify the IP addresses in IPv4 or IPv6 or a subnet using CIDR notation.
      Restrictions restrictions = Restrictions.newBuilder()
          .setServerKeyRestrictions(ServerKeyRestrictions.newBuilder()
              .addAllAllowedIps(Arrays.asList("198.51.100.0/24", "2000:db8::/64"))
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

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


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key

def restrict_api_key_server(project_id: str, key_id: str) -> Key:
    """
    Restricts the API key based on IP addresses. You can specify one or more IP addresses of the callers,
    for example web servers or cron jobs, that are allowed to use your API key.

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

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage by specifying the IP addresses.
    # You can specify the IP addresses in IPv4 or IPv6 or a subnet using CIDR notation.
    server_key_restrictions = api_keys_v2.ServerKeyRestrictions()
    server_key_restrictions.allowed_ips = ["198.51.100.0/24", "2000:db8::/64"]

    # Set the API restriction.
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.server_key_restrictions = server_key_restrictions

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 制限するキーの ID を取得します。

    ID は表示名やキー文字列とは異なります。ID を取得するには、keys.list メソッドを使用します。ID はレスポンスの uid フィールドに示されます。

    PROJECT_ID は、Google Cloud プロジェクト ID または名前に置き換えます。

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys./v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. keys.patch メソッドを使用して、サーバー(IP アドレス)の制限を API キーに追加します。

    このリクエストは、長時間実行オペレーションを返します。オペレーションをポーリングして、オペレーションが完了したタイミングを把握し、オペレーションのステータスを取得する必要があります。

    次の値を置き換えます。

    • ALLOWED_IP_ADDR_1: 許可する IP アドレス。

      IP アドレスは必要な数だけ追加できます。制限はカンマで区切ります。すべての IP アドレスにリクエストを指定する必要があります。指定したリファラー制限により、キー上の任意の既存の IP アドレス制限が置き換えられます。

    • PROJECT_ID: Google Cloud プロジェクト ID または名前。

    • KEY_ID: 制限するキーの ID。

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
      "serverKeyRestrictions": {
        "allowedIps": ["ALLOWED_IP_ADDR_1"]
      }
    }
    }' \
    "https://apikeys./v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

REST API を使用してキーに IP アドレスの制限を追加する方法について詳しくは、API Keys API ドキュメントのサーバー制限の追加をご覧ください。

Android アプリ

API キーの使用を特定の Android アプリに制限できます。アプリごとに、パッケージ名と 20 バイトの SHA-1 証明書のフィンガープリントを指定する必要があります。

リクエストで API キーを使用する場合は、次の HTTP ヘッダーを使用してパッケージ名と証明書フィンガープリントを指定する必要があります。

  • X-Android-Package
  • X-Android-Cert

API キーを 1 つ以上の Android アプリに制限するには、次のいずれかのオプションを使用します。

コンソール

  1. Google Cloud コンソールで、[認証情報] ページに移動します。

    [認証情報] に移動

  2. 制限する API キーの名前をクリックします。

  3. [アプリケーションの制限] で、[Android アプリ] を選択します。

  4. 追加する Android アプリごとに、[項目を追加] をクリックし、パッケージ名と SHA-1 証明書のフィンガープリントを入力して、[完了] をクリックします。

  5. [保存] をクリックして変更を保存し、API キーリストに戻ります。

gcloud

  1. 制限するキーの ID を取得します。

    ID は表示名やキー文字列とは異なります。ID を取得するには、gcloud services api-keys list コマンドを使用して、プロジェクト内のキーを一覧表示します。

  2. API キーを使用できる Android アプリを指定するには、gcloud beta services api-keys update コマンドを使用します。

    次の値を置き換えます。

    • KEY_ID: 制限するキーの ID。
    • SHA1_FINGERPRINTPACKAGE_NAME: キーを使用できる Android アプリのアプリ情報。

      アプリは必要に応じていくつでも追加できます。追加の --allowed-application フラグを使用します。

    gcloud beta services api-keys update KEY_ID \
    --allowed-application=sha1_fingerprint=SHA1_FINGERPRINT_1,package_name=PACKAGE_NAME_1 \
    --allowed-application=sha1_fingerprint=SHA1_FINGERPRINT_2,package_name=PACKAGE_NAME_2
    

Java

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


import com.google.api.apikeys.v2.AndroidApplication;
import com.google.api.apikeys.v2.AndroidKeyRestrictions;
import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyAndroid {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyAndroid(projectId, keyId);
  }

  // Restricts an API key based on android applications.
  // Specifies the Android application that can use the key.
  public static void restrictApiKeyAndroid(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the allowed android applications.
      Restrictions restrictions = Restrictions.newBuilder()
          .setAndroidKeyRestrictions(AndroidKeyRestrictions.newBuilder()
              .addAllowedApplications(AndroidApplication.newBuilder()
                  // Specify the android application's package name and SHA1 fingerprint.
                  .setPackageName("com.google.appname")
                  .setSha1Fingerprint("0873D391E987982FBBD30873D391E987982FBBD3")
                  .build())
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

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


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key

def restrict_api_key_android(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key based on android applications.

    Specifies the Android application that can use the key.

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

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Specify the android application's package name and SHA1 fingerprint.
    allowed_application = api_keys_v2.AndroidApplication()
    allowed_application.package_name = "com.google.appname"
    allowed_application.sha1_fingerprint = "0873D391E987982FBBD30873D391E987982FBBD3"

    # Restrict the API key usage by specifying the allowed applications.
    android_key_restriction = api_keys_v2.AndroidKeyRestrictions()
    android_key_restriction.allowed_applications = [allowed_application]

    # Set the restriction(s).
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.android_key_restrictions = android_key_restriction

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 制限するキーの ID を取得します。

    ID は表示名やキー文字列とは異なります。ID を取得するには、keys.list メソッドを使用します。ID はレスポンスの uid フィールドに示されます。

    PROJECT_ID は、Google Cloud プロジェクト ID または名前に置き換えます。

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys./v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. keys.patch メソッドを使用して、API キーを使用できる Android アプリを指定します。

    このリクエストは、長時間実行オペレーションを返します。オペレーションをポーリングして、オペレーションが完了したタイミングを把握し、オペレーションのステータスを取得する必要があります。

    次の値を置き換えます。

    • SHA1_FINGERPRINT_1PACKAGE_NAME_1: キーを使用できる Android アプリのアプリ情報。

      情報は必要な数のアプリに追加できます。AndroidApplication オブジェクトを区切るにはカンマを使用します。すべてのアプリケーションにリクエストを提供する必要があります。指定したアプリケーションにより、キー上の任意の既存のアプリケーションが置き換えられます。

    • PROJECT_ID: Google Cloud プロジェクト ID または名前。

    • KEY_ID: 制限するキーの ID。

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "androidKeyRestrictions": {
      "allowedApplications": [
        {
          "sha1Fingerprint": "SHA1_FINGERPRINT_1",
          "packageName": "PACKAGE_NAME_1"
        },
     ]
    }
    }
    }' \
    "https://apikeys./v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

REST API を使用してキーに Android アプリの制限を追加する方法については、API Keys API ドキュメントの Android の制限の追加をご覧ください。

iOS アプリ

各アプリのバンドル ID を指定して、特定の iOS アプリに API キーの使用を制限できます。

リクエストで API キーを使用する場合は、X-Ios-Bundle-Identifier HTTP ヘッダーを使用してバンドル ID を指定する必要があります。

API キーを 1 つ以上の iOS アプリに制限するには、次のいずれかのオプションを使用します。

コンソール

  1. Google Cloud コンソールで、[認証情報] ページに移動します。

    [認証情報] に移動

  2. 制限する API キーの名前をクリックします。

  3. [アプリケーションの制限] で、[iOS アプリ] を選択します。

  4. 追加する iOS アプリごとに [項目を追加] をクリックし、バンドル ID を入力して、[完了] をクリックします。

  5. [保存] をクリックして変更を保存し、API キーリストに戻ります。

gcloud

  1. 制限するキーの ID を取得します。

    ID は表示名やキー文字列とは異なります。ID を取得するには、gcloud services api-keys list コマンドを使用して、プロジェクト内のキーを一覧表示します。

  2. gcloud beta services api-keys update メソッドを使用して、キーを使用できる iOS アプリを指定します。

    次の値を置き換えます。

    • KEY_ID: 制限するキーの ID。
    • ALLOWED_BUNDLE_ID: この API キーを使用できるようにする iOS アプリのバンドル ID。

      バンドル ID は必要な数だけ追加できます。ID はカンマで区切ります。

    gcloud beta services api-keys update KEY_ID \
    --allowed-bundle-ids=ALLOWED_BUNDLE_ID_1,ALLOWED_BUNDLE_ID_2
    

Java

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


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.IosKeyRestrictions;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyIos {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyIos(projectId, keyId);
  }

  // Restricts an API key. You can restrict usage of an API key to specific iOS apps
  // by providing the bundle ID of each app.
  public static void restrictApiKeyIos(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the bundle ID(s)
      // of iOS app(s) that can use the key.
      Restrictions restrictions = Restrictions.newBuilder()
          .setIosKeyRestrictions(IosKeyRestrictions.newBuilder()
              .addAllAllowedBundleIds(Arrays.asList("com.google.gmail", "com.google.drive"))
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

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


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key

def restrict_api_key_ios(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key. You can restrict usage of an API key to specific iOS apps
    by providing the bundle ID of each app.

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

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage by specifying the bundle ID(s) of iOS app(s) that can use the key.
    ios_key_restrictions = api_keys_v2.IosKeyRestrictions()
    ios_key_restrictions.allowed_bundle_ids = ["com.google.gmail", "com.google.drive"]

    # Set the API restriction.
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.ios_key_restrictions = ios_key_restrictions

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 制限するキーの ID を取得します。

    ID は表示名やキー文字列とは異なります。ID を取得するには、keys.list メソッドを使用します。ID はレスポンスの uid フィールドに示されます。

    PROJECT_ID は、Google Cloud プロジェクト ID または名前に置き換えます。

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys./v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. API キーを使用できる iOS アプリを指定するには、keys.patch メソッドを使用します。

    このリクエストは、長時間実行オペレーションを返します。オペレーションをポーリングして、オペレーションが完了したタイミングを把握し、オペレーションのステータスを取得する必要があります。

    次の値を置き換えます。

    • ALLOWED_BUNDLE_ID: キーを使用できる iOS アプリのバンドル ID。

      情報は必要な数のアプリに追加できます。バンドル ID はカンマで区切ります。すべてのバンドル ID にリクエストを指定する必要があります。指定したバンドル ID により、そのキーで許可されている既存のアプリケーションが置き換えられます。

    • PROJECT_ID: Google Cloud プロジェクト ID または名前。

    • KEY_ID: 制限するキーの ID。

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "iosKeyRestrictions": {
      "allowedBundleIds": ["ALLOWED_BUNDLE_ID_1","ALLOWED_BUNDLE_ID_2"]
    }
    }
    }' \
    "https://apikeys./v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

REST API を使用してキーに iOS アプリの制限を追加する方法については、API Keys API ドキュメントの iOS の制限の追加をご覧ください。

API 制限を追加する

API の制限では、API キーを使用した呼び出しを許可する API を指定します。

API 制限を追加するには、次のいずれかの方法を使用します。

コンソール

  1. Google Cloud コンソールで、[認証情報] ページに移動します。

    [認証情報] に移動

  2. 制限する API キーの名前をクリックします。

  3. [API の制限] セクションで、[キーを制限] をクリックします。

  4. API キーをアクセスに使用するすべての API を選択します。

  5. [保存] をクリックして変更を保存し、API キーリストに戻ります。

gcloud

  1. 制限するキーの ID を取得します。

    ID は表示名やキー文字列とは異なります。ID を取得するには、gcloud services api-keys list コマンドを使用して、プロジェクト内のキーを一覧表示します。

  2. gcloud beta services api-keys update コマンドを使用して、API キーで認証できるサービスを指定します。

    次の値を置き換えます。

    • KEY_ID: 制限するキーの ID。
    • SERVICE_1SERVICE_2...: キーへのアクセスに使用できる API のサービス名。

      update コマンドでは、すべてのサービス名を指定する必要があります。指定されたサービス名がキーの既存のサービスを置き換えます。

    サービス名を確認するには、API ダッシュボードで API を検索します。サービス名は bigquery.googleapis.com のような文字列です。

    gcloud beta services api-keys update KEY_ID \
    --api-target=service=SERVICE_1 --api-target=service=SERVICE_2
    

Java

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


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.ApiTarget;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyApi {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyApi(projectId, keyId);
  }

  // Restricts an API key. Restrictions specify which APIs can be called using the API key.
  public static void restrictApiKeyApi(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the target service and methods.
      // The API key can only be used to authenticate the specified methods in the service.
      Restrictions restrictions = Restrictions.newBuilder()
          .addApiTargets(ApiTarget.newBuilder()
              .setService("translate.googleapis.com")
              .addMethods("translate.googleapis.com.TranslateText")
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

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


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key

def restrict_api_key_api(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key. Restrictions specify which APIs can be called using the API key.

    TODO(Developer): Replace the variables before running the sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage by specifying the target service and methods.
    # The API key can only be used to authenticate the specified methods in the service.
    api_target = api_keys_v2.ApiTarget()
    api_target.service = "translate.googleapis.com"
    api_target.methods = ["transate.googleapis.com.TranslateText"]

    # Set the API restriction(s).
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.api_targets = [api_target]

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 制限するキーの ID を取得します。

    ID は表示名やキー文字列とは異なります。ID を取得するには、keys.list メソッドを使用します。ID はレスポンスの uid フィールドに示されます。

    PROJECT_ID は、Google Cloud プロジェクト ID または名前に置き換えます。

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys./v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. keys.patch メソッドを使用して、API キーで認証できるサービスを指定します。

    このリクエストは、長時間実行オペレーションを返します。オペレーションをポーリングして、オペレーションが完了したタイミングを把握し、オペレーションのステータスを取得する必要があります。

    次の値を置き換えます。

    • SERVICE_1SERVICE_2...: キーへのアクセスに使用できる API のサービス名。

      リクエストにはすべてのサービス名を指定する必要があります。指定されたサービス名がキーの既存のサービスを置き換えます。

      サービス名を確認するには、API ダッシュボードで API を検索します。サービス名は bigquery.googleapis.com のような文字列です。

    • PROJECT_ID: Google Cloud プロジェクト ID または名前。

    • KEY_ID: 制限するキーの ID。

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "apiTargets": [
      {
        "service": "SERVICE_1"
      },
      {
        "service" : "SERVICE_2"
      },
    ]
    }
    }' \
    "https://apikeys./v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

REST API を使用してキーに API の制限を追加する方法については、API Keys API ドキュメントの API の制限の追加をご覧ください。

キー文字列からプロジェクト情報を取得する

API キーがどの Google Cloud プロジェクトに関連付けられているかは、その文字列から判断できます。

KEY_STRING は、プロジェクト情報が必要なキー文字列に置き換えます。

gcloud

gcloud beta services api-keys lookup コマンドを使用して、キー文字列からプロジェクト ID を取得します。

 gcloud beta services api-keys lookup KEY_STRING
 

Java

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


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.LookupKeyRequest;
import com.google.api.apikeys.v2.LookupKeyResponse;
import java.io.IOException;

public class LookupApiKey {

  public static void main(String[] args) throws IOException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    //  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 view API keys.
    // API key string to retrieve the API key name.
    String apiKeyString = "API_KEY_STRING";

    lookupApiKey(apiKeyString);
  }

  // Retrieves name (full path) of an API key using the API key string.
  public static void lookupApiKey(String apiKeyString) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Initialize the lookup request and set the API key string.
      LookupKeyRequest lookupKeyRequest = LookupKeyRequest.newBuilder()
          .setKeyString(apiKeyString)
          .build();

      // Make the request and obtain the response.
      LookupKeyResponse response = apiKeysClient.lookupKey(lookupKeyRequest);

      System.out.printf("Successfully retrieved the API key name: %s", response.getName());
    }
  }
}

Python

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


from google.cloud import api_keys_v2

def lookup_api_key(api_key_string: str) -> None:
    """
    Retrieves name (full path) of an API key using the API key string.

    TODO(Developer):
    1. Before running this sample,
      set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    2. Make sure you have the necessary permission to view API keys.

    Args:
        api_key_string: API key string to retrieve the API key name.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Initialize the lookup request and set the API key string.
    lookup_key_request = api_keys_v2.LookupKeyRequest(
        key_string=api_key_string,
        # Optionally, you can also set the etag (version).
        # etag=etag,
    )

    # Make the request and obtain the response.
    lookup_key_response = client.lookup_key(lookup_key_request)

    print(f"Successfully retrieved the API key name: {lookup_key_response.name}")

REST

lookupKey メソッドを使用して、キー文字列からプロジェクト ID を取得します。

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
"https://apikeys./v2/keys:lookupKey?keyString=KEY_STRING"

API キーの削除を取り消す

API キーを誤って削除した場合、キーを削除してから 30 日以内であれば、そのキーの削除を取り消す(復元する)ことができます。30 日を経過すると、API キーの削除を取り消すことはできません。

コンソール

  1. Google Cloud コンソールで、[認証情報] ページに移動します。

    [認証情報] に移動

  2. [削除した認証情報を復元] をクリックします。

  3. 復元したい API キーを探して、そのキーの [復元] をクリックします。

    API キーの削除が取り消されるまでに、数分かかることがあります。反映されると、削除を取り消した API キーが API キーのリストに表示されます。

gcloud

  1. 削除を取り消すキーの ID を取得します。

    ID は表示名やキー文字列とは異なります。ID を取得するには、gcloud services api-keys list --show-deleted コマンドを使用して、プロジェクトで削除されたキーを一覧表示します。

  2. API キーの削除を取り消すには、gcloud beta services api-keys undelete コマンドを使用します。

    gcloud beta services api-keys undelete KEY_ID
    

    次の値を置き換えます。

    • KEY_ID: 削除を取り消すキーの ID。

REST

  1. 削除を取り消すキーの ID を取得します。

    ID は表示名やキー文字列とは異なります。ID を取得するには、showDeleted クエリ パラメータを true に設定して、keys.list メソッドを使用します。キー ID はレスポンスの uid フィールドに示されます。

    PROJECT_ID は、Google Cloud プロジェクト ID または名前に置き換えます。

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys./v2/projects/PROJECT_ID/locations/global/keys?showDeleted=true"
    
  2. API キーの削除を取り消すには、undelete メソッドを使用します。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://apikeys./v2/projects/PROJECT_ID/locations/global/keys/KEY_ID:undelete"
    

    このリクエストは、長時間実行オペレーションを返します。オペレーションをポーリングして、オペレーションが完了したタイミングを把握し、オペレーションのステータスを取得する必要があります。

    次の値を置き換えます。

    • PROJECT_ID: Google Cloud プロジェクト ID または名前。
    • KEY_ID: 制限するキーの ID。

長時間実行オペレーションをポーリングする

API Keys API メソッドは、長時間実行オペレーションを使用します。REST API を使用して API キーの作成と管理を行う場合は、最初のメソッドのリクエストからオペレーション オブジェクトが返されます。オペレーション名を使用して、長時間実行オペレーションをポーリングします。長時間実行リクエストが完了したときに、オペレーションをポーリングすると、長時間実行リクエストからデータが返されます。

長時間実行 API Keys API オペレーションをポーリングするには、operations.get メソッドを使用します。

OPERATION_NAME は、長時間実行オペレーションによって返されたオペレーション名に置き換えます。例: operations/akmf.p7-358517206116-cd10a88a-7740-4403-a8fd-979f3bd7fe1c

curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://apikeys./v2/OPERATION_NAME"

API キーの制限

プロジェクトごとに最大 300 個の API キーを作成できます。これはシステム上の上限です。割り当て増加リクエストを使用して変更することはできません。

API キーがさらに必要な場合は、複数のプロジェクトを使用する必要があります。

次のステップ