Melakukan autentikasi menggunakan kunci API

Halaman ini menjelaskan cara menggunakan kunci API untuk mengautentikasi ke Google Cloud API dan layanan yang mendukung kunci API.

Sebagian besar Google Cloud API tidak mendukung kunci API. Pastikan API yang ingin Anda gunakan mendukung kunci API sebelum menggunakan metode autentikasi ini.

Pengantar kunci API

Saat Anda menggunakan kunci API untuk mengautentikasi ke API, kunci API tidak mengidentifikasi akun utama, juga tidak memberikan informasi otorisasi apa pun. Oleh karena itu, permintaan tersebut tidak menggunakan Identity and Access Management (IAM) untuk memeriksa apakah pemanggil memiliki izin untuk melakukan operasi yang diminta.

Kunci API mengaitkan permintaan dengan project Google Cloud untuk tujuan penagihan dan kuota. Karena tidak mengidentifikasi pemanggil, kunci API sering kali digunakan untuk mengakses data atau resource publik.

Banyak Google Cloud API yang tidak menerima kunci API untuk autentikasi. Tinjau dokumentasi autentikasi untuk layanan atau API yang ingin Anda gunakan untuk menentukan apakah layanan atau API tersebut mendukung kunci API atau tidak.

Kunci API memiliki komponen berikut, yang Anda gunakan untuk mengelola dan menggunakan kunci:

String
String kunci API adalah string terenkripsi, misalnya, AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe. Saat menggunakan kunci API untuk mengautentikasi, Anda akan selalu menggunakan string kunci tersebut. Kunci API tidak memiliki file JSON terkait.
ID
ID kunci API digunakan oleh alat administratif Google Cloud untuk mengidentifikasi kunci secara unik. ID kunci tidak dapat digunakan untuk autentikasi. ID kunci dapat ditemukan di URL halaman edit kunci di konsol Google Cloud. Anda juga bisa mendapatkan ID kunci dengan menggunakan Google Cloud CLI untuk mencantumkan kunci di project Anda.
Nama tampilan
Nama tampilan adalah nama deskriptif opsional untuk kunci, yang dapat Anda tetapkan saat membuat atau mengupdate kunci.

Untuk mengelola kunci API, Anda harus memiliki peran API Keys Admin (roles/serviceusage.apiKeysAdmin) pada project.

Sebelum memulai

Pilih tab untuk melihat bagaimana Anda berencana menggunakan contoh di halaman ini:

Konsol

Saat menggunakan Konsol Google Cloud untuk mengakses API dan layanan Google Cloud, Anda tidak perlu menyiapkan autentikasi.

gcloud

Anda dapat menggunakan sampel gcloud CLI di halaman ini dari salah satu lingkungan pengembangan berikut:

  • Cloud Shell: Untuk menggunakan terminal online dengan gcloud CLI yang sudah disiapkan, aktifkan Cloud Shell.

    Di bagian bawah halaman ini, sesi Cloud Shell akan dimulai dan menampilkan perintah command line. Perlu waktu beberapa detik hingga sesi dimulai.

  • Shell lokal: Untuk menggunakan gcloud CLI di lingkungan pengembangan lokal, instal dan initialize gcloud CLI.

Java

Untuk menggunakan contoh Java di halaman ini dari lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

  1. Menginstal Google Cloud CLI.
  2. Untuk initialize gcloud CLI, jalankan perintah berikut:

    gcloud init
  3. Buat kredensial autentikasi lokal untuk Akun Google Anda:

    gcloud auth application-default login

Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal dalam dokumentasi autentikasi Google Cloud.

Python

Untuk menggunakan contoh Python di halaman ini dari lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

  1. Menginstal Google Cloud CLI.
  2. Untuk initialize gcloud CLI, jalankan perintah berikut:

    gcloud init
  3. Buat kredensial autentikasi lokal untuk Akun Google Anda:

    gcloud auth application-default login

Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal dalam dokumentasi autentikasi Google Cloud.

REST

Untuk menggunakan contoh REST API di halaman ini dalam lingkungan pengembangan lokal, gunakan kredensial yang Anda berikan ke gcloud CLI.

    Instal Google Cloud CLI, lalu initialize dengan menjalankan perintah berikut:

    gcloud init

Membuat kunci API

Untuk membuat kunci API, gunakan salah satu opsi berikut:

Konsol

  1. Di konsol Google Cloud, buka halaman Credentials.

    Buka Credentials

  2. Klik Create credentials, lalu pilih API key dari menu.

    Dialog API key created akan menampilkan string untuk kunci yang baru dibuat.

gcloud

Gunakan perintah gcloud beta services api-keys create untuk membuat kunci API.

Ganti DISPLAY_NAME dengan nama deskriptif untuk kunci Anda.

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

Java

Untuk menjalankan contoh ini, Anda harus menginstal library klien 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

Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci 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

Gunakan metode keys.create untuk membuat kunci API. Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mendapatkan informasi tentang kunci yang baru.

Ganti nilai berikut:

  • DISPLAY_NAME: Opsional. Nama deskriptif untuk kunci Anda.
  • PROJECT_ID: Project ID atau nama project Google Cloud Anda.
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.googleapis.com/v2/projects/PROJECT/locations/global/keys"

Untuk informasi lebih lanjut tentang membuat kunci API menggunakan REST API, lihat Membuat kunci API dalam dokumentasi API Keys API.

Salin string kunci Anda dan amankan. Kecuali jika Anda menggunakan kunci pengujian yang ingin Anda hapus nanti, tambahkan pembatasan kunci aplikasi dan API.

Menggunakan kunci API

Jika API mendukung penggunaan kunci API, Anda bisa menggunakan kunci API untuk mengautentikasi API tersebut. Anda menggunakan kunci API dengan permintaan REST dan dengan library klien yang mendukungnya.

Menggunakan kunci API dengan REST

Anda dapat meneruskan kunci API ke dalam panggilan REST API sebagai parameter kueri dengan format berikut. Ganti API_KEY dengan string kunci dari kunci API Anda.

Misalnya, untuk meneruskan kunci API bagi permintaan Cloud Natural Language API untuk documents.analyzeEntities:

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY

Atau, Anda dapat menggunakan header x-goog-api-key untuk meneruskan kunci. Header ini harus digunakan dengan permintaan gRPC.

curl -X POST \
    -H "X-goog-api-key: API_KEY" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://translation.googleapis.com/language/translate/v2"

Menggunakan kunci API dengan library klien

Dukungan library klien untuk kunci API bersifat spesifik per bahasa.

Python

Contoh ini menggunakan Cloud Natural Language API, yang mendukung kunci API untuk autentikasi, untuk menunjukkan cara menyediakan kunci API ke library.

Untuk menjalankan contoh ini, Anda harus menginstal library klien Natural Language dan library klien Kunci API.


from google.cloud import language_v1

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

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

    Args:
        quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
        api_key_string: The API key to authenticate to the service.
    """

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

    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")

Mengamankan kunci API

Saat Anda menggunakan kunci API di aplikasi, pastikan kunci tersebut tetap aman selama penyimpanan dan transmisi. Menampilkan kunci API kepada publik dapat menyebabkan tagihan tidak terduga pada akun Anda. Untuk membantu menjaga kunci API Anda tetap aman, ikuti praktik terbaik berikut:

  • Tambahkan pembatasan kunci API ke kunci Anda.

    Dengan menambahkan batasan, Anda dapat membatasi penggunaan kunci API, sehingga mengurangi dampak kunci API yang disusupi.

  • Hapus kunci API yang tidak diperlukan untuk meminimalkan paparan serangan.

  • Buat ulang kunci API Anda secara berkala.

    Buat kunci API baru secara berkala, hapus kunci lama, dan update aplikasi Anda untuk menggunakan kunci API baru.

Menerapkan pembatasan kunci API

Kunci API tidak dibatasi secara default. Kunci yang tidak dibatasi tidak aman karena dapat digunakan oleh siapa saja dari mana saja. Untuk aplikasi produksi, Anda harus menetapkan pembatasan aplikasi dan pembatasan API.

Menambahkan batasan aplikasi

Pembatasan aplikasi menentukan situs, alamat IP, atau aplikasi mana yang dapat menggunakan kunci API.

Anda hanya dapat menerapkan satu jenis pembatasan aplikasi dalam satu waktu. Pilih jenis pembatasan berdasarkan jenis aplikasi Anda:

Opsi Jenis aplikasi Notes
Perujuk HTTP Aplikasi web Menentukan situs yang dapat menggunakan kunci tersebut.
Alamat IP Aplikasi yang dipanggil oleh server tertentu Menentukan server atau cron job yang dapat menggunakan kunci tersebut.
Aplikasi Android Aplikasi Android Menentukan aplikasi Android yang dapat menggunakan kunci tersebut.
Aplikasi iOS Aplikasi iOS Menentukan paket iOS yang dapat menggunakan kunci tersebut.

Perujuk HTTP

Untuk membatasi situs yang dapat menggunakan kunci API Anda, tambahkan satu atau beberapa pembatasan perujuk HTTP.

Anda dapat mengganti karakter pengganti (*) untuk subdomain atau jalur, tetapi Anda tidak dapat menyisipkan karakter pengganti ke tengah URL. Misalnya, *.google.com valid, dan menerima semua situs yang diakhiri dengan .google.com. Namun, mysubdomain*.google.com bukan batasan yang valid.

Nomor port dapat disertakan dalam pembatasan perujuk HTTP. Jika Anda menyertakan nomor port, hanya permintaan yang menggunakan port tersebut yang akan dicocokkan. Jika Anda tidak menentukan nomor port, permintaan dari nomor port mana pun akan dicocokkan.

Anda bisa menambahkan hingga 1200 perujuk HTTP ke kunci API.

Tabel berikut menunjukkan beberapa skenario contoh dan pembatasan browser:

Skenario Pembatasan
Mengizinkan URL tertentu Menambahkan URL dengan jalur yang tepat. Contoh:
www.example.com/path
www.example.com/path/path

Beberapa browser menerapkan kebijakan perujuk yang hanya mengirim URL asal untuk permintaan lintas asal. Pengguna browser ini tidak dapat menggunakan kunci dengan pembatasan URL khusus halaman.

Izinkan URL apa pun di situs Anda Anda harus menetapkan dua URL dalam daftar allowedReferers.
  1. URL untuk domain, tanpa subdomain, dan dengan karakter pengganti untuk jalur. Contoh:
    example.com/*
  2. URL kedua yang menyertakan karakter pengganti untuk subdomain dan karakter pengganti untuk jalur. Contoh:
    *.example.com/*
Mengizinkan URL apa pun pada subdomain tunggal atau domain tanpa awalan www

Anda harus menetapkan dua URL dalam daftar allowedReferers untuk mengizinkan seluruh domain:

  1. URL untuk domain, tanpa garis miring setelahnya. Contoh:
    www.example.com
    sub.example.com
    example.com
  2. URL kedua untuk domain yang menyertakan karakter pengganti untuk jalur. Contoh:
    www.example.com/*
    sub.example.com/*
    example.com/*

Untuk membatasi kunci API Anda ke situs tertentu, gunakan salah satu opsi berikut:

Konsol

  1. Di konsol Google Cloud, buka halaman Credentials.

    Buka Credentials

  2. Klik nama kunci API yang ingin Anda batasi.

  3. Di bagian Application restrictions, pilih HTTP referrers.

  4. Untuk setiap batasan yang ingin ditambahkan, klik Add an item, masukkan batasan, lalu klik Done.

  5. Klik Save untuk menyimpan perubahan dan kembali ke daftar kunci API.

gcloud

  1. Dapatkan ID kunci yang ingin Anda batasi.

    ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini dengan menggunakan perintah gcloud services api-keys list untuk menampilkan daftar kunci dalam project Anda.

  2. Gunakan perintah gcloud beta services api-keys update untuk menambahkan batasan perujuk HTTP ke kunci API.

    Ganti nilai berikut:

    • KEY_ID: ID kunci yang ingin Anda batasi.
    • ALLOWED_REFERRER_1: Pembatasan perujuk HTTP Anda.

      Anda dapat menambahkan pembatasan sebanyak yang diperlukan; gunakan koma untuk memisahkan batasan tersebut. Anda harus memberikan semua batasan perujuk dengan perintah update; pembatasan perujuk yang diberikan menggantikan pembatasan perujuk yang ada pada kunci tersebut.

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

Java

Untuk menjalankan contoh ini, Anda harus menginstal library klien 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

Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci 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. Dapatkan ID kunci yang ingin Anda batasi.

    ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini menggunakan metode keys.list. ID tercantum di kolom uid respons.

    Ganti PROJECT_ID dengan ID atau nama project Google Cloud Anda.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. Gunakan metode keys.patch untuk menambahkan pembatasan perujuk HTTP pada kunci API.

    Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mengetahui kapan operasi selesai dan mendapatkan status operasi.

    Ganti nilai berikut:

    • ALLOWED_REFERRER_1: Pembatasan perujuk HTTP Anda.

      Anda dapat menambahkan pembatasan sebanyak yang diperlukan; gunakan koma untuk memisahkan batasan tersebut. Anda harus memberikan semua batasan perujuk dengan permintaan tersebut; pembatasan perujuk yang diberikan menggantikan pembatasan perujuk yang ada pada kunci tersebut.

    • PROJECT_ID: Project ID atau nama project Google Cloud Anda.

    • KEY_ID: ID kunci yang ingin Anda batasi.

    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.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

Untuk informasi selengkapnya tentang menambahkan pembatasan perujuk HTTP ke kunci menggunakan REST API, lihat Menambahkan pembatasan browser dalam dokumentasi API Keys API.

Alamat IP

Anda dapat menentukan satu atau beberapa alamat IP pemanggil, seperti server web atau cron job, yang diizinkan untuk menggunakan kunci API Anda. Anda dapat menentukan alamat IP dalam salah satu format berikut:

  • IPv4 (198.51.100.1)
  • IPv6 (2001:db8::1)
  • Subnet yang menggunakan notasi CIDR (198.51.100.0/24, 2001:db8::/64)

Penggunaan localhost tidak didukung untuk pembatasan server.

Untuk membatasi kunci API Anda ke alamat IP tertentu, gunakan salah satu opsi berikut:

Konsol

  1. Di konsol Google Cloud, buka halaman Credentials.

    Buka Credentials

  2. Klik nama kunci API yang ingin Anda batasi.

  3. Di bagian Application restrictions, pilih IP addresses.

  4. Untuk setiap alamat IP yang ingin ditambahkan, klik Add an item, masukkan alamat, lalu klik Done.

  5. Klik Save untuk menyimpan perubahan dan kembali ke daftar kunci API.

gcloud

  1. Dapatkan ID kunci yang ingin Anda batasi.

    ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini dengan menggunakan perintah gcloud services api-keys list untuk menampilkan daftar kunci dalam project Anda.

  2. Gunakan perintah gcloud beta services api-keys update untuk menambahkan pembatasan server (alamat IP) ke kunci API.

    Ganti nilai berikut:

    • KEY_ID: ID kunci yang ingin Anda batasi.
    • ALLOWED_IP_ADDR_1: Alamat IP yang diizinkan.

      Anda dapat menambahkan alamat IP sebanyak yang diperlukan; menggunakan koma untuk memisahkan alamat.

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

Java

Untuk menjalankan contoh ini, Anda harus menginstal library klien 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

Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci 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. Dapatkan ID kunci yang ingin Anda batasi.

    ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini menggunakan metode keys.list. ID tercantum di kolom uid respons.

    Ganti PROJECT_ID dengan project ID atau nama project Google Cloud Anda.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. Gunakan metode keys.patch untuk menambahkan pembatasan server (alamat IP) ke kunci API.

    Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mengetahui kapan operasi selesai dan mendapatkan status operasi.

    Ganti nilai berikut:

    • ALLOWED_IP_ADDR_1: Alamat IP yang diizinkan.

      Anda dapat menambahkan alamat IP sebanyak yang diperlukan; menggunakan koma untuk memisahkan batasan. Anda harus memberikan semua alamat IP dengan permintaan; pembatasan perujuk yang disediakan menggantikan pembatasan alamat IP yang ada pada kunci tersebut.

    • PROJECT_ID: Project ID atau nama project Google Cloud Anda.

    • KEY_ID: ID kunci yang ingin Anda batasi.

    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.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

Untuk informasi selengkapnya tentang menambahkan pembatasan alamat IP ke kunci menggunakan REST API, lihat Menambahkan pembatasan server dalam dokumentasi API Keys API.

Aplikasi Android

Anda dapat membatasi penggunaan kunci API untuk aplikasi Android tertentu. Anda harus memberikan nama paket dan sidik jari sertifikat SHA-1 20 byte untuk setiap aplikasi.

Saat menggunakan kunci API dalam permintaan, Anda harus menentukan nama paket dan sidik jari sertifikat menggunakan header HTTP berikut:

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

Untuk membatasi kunci API Anda ke satu atau beberapa aplikasi Android, gunakan salah satu opsi berikut:

Konsol

  1. Di konsol Google Cloud, buka halaman Credentials.

    Buka Credentials

  2. Klik nama kunci API yang ingin Anda batasi.

  3. Di bagian Application restrictions, pilih Android apps.

  4. Untuk setiap aplikasi Android yang ingin ditambahkan, klik Add an item dan masukkan nama paket serta sidik jari sertifikat SHA-1, lalu klik Done.

  5. Klik Save untuk menyimpan perubahan dan kembali ke daftar kunci API.

gcloud

  1. Dapatkan ID kunci yang ingin Anda batasi.

    ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini dengan menggunakan perintah gcloud services api-keys list untuk menampilkan daftar kunci dalam project Anda.

  2. Gunakan perintah gcloud beta services api-keys update untuk menentukan aplikasi Android yang dapat menggunakan kunci API.

    Ganti nilai berikut:

    • KEY_ID: ID kunci yang ingin Anda batasi.
    • SHA1_FINGERPRINT dan PACKAGE_NAME: Informasi aplikasi untuk aplikasi Android yang dapat menggunakan kunci tersebut.

      Anda dapat menambahkan aplikasi sebanyak yang diperlukan; gunakan flag --allowed-application tambahan.

    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

Untuk menjalankan contoh ini, Anda harus menginstal library klien 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

Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci 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. Dapatkan ID kunci yang ingin Anda batasi.

    ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini menggunakan metode keys.list. ID tercantum di kolom uid respons.

    Ganti PROJECT_ID dengan ID atau nama project Google Cloud Anda.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. Gunakan metode keys.patch untuk menentukan aplikasi Android yang dapat menggunakan kunci API.

    Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mengetahui kapan operasi selesai dan mendapatkan status operasi.

    Ganti nilai berikut:

    • SHA1_FINGERPRINT_1 dan PACKAGE_NAME_1: Informasi aplikasi untuk aplikasi Android yang dapat menggunakan kunci tersebut.

      Anda dapat menambahkan informasi untuk aplikasi sebanyak yang dibutuhkan; gunakan koma untuk memisahkan objek AndroidApplication. Anda harus memberikan permintaan kepada semua aplikasi; aplikasi yang disediakan menggantikan aplikasi yang diizinkan pada kunci tersebut.

    • PROJECT_ID: Project ID atau nama project Google Cloud Anda.

    • KEY_ID: ID kunci yang ingin Anda batasi.

    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.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

Untuk informasi selengkapnya tentang menambahkan pembatasan aplikasi Android ke kunci menggunakan REST API, lihat Menambahkan pembatasan Android dalam dokumentasi API Keys API.

Aplikasi iOS

Anda dapat membatasi penggunaan kunci API untuk aplikasi iOS tertentu dengan memberikan ID paket setiap aplikasi.

Jika menggunakan kunci API dalam permintaan, Anda harus menentukan ID paket menggunakan header HTTP X-Ios-Bundle-Identifier.

Untuk membatasi kunci API Anda ke satu atau beberapa aplikasi iOS, gunakan salah satu opsi berikut:

Konsol

  1. Di konsol Google Cloud, buka halaman Credentials.

    Buka Credentials

  2. Klik nama kunci API yang ingin Anda batasi.

  3. Di bagian Application restrictions, pilih iOS apps.

  4. Untuk setiap aplikasi iOS yang ingin Anda tambahkan, klik Add an item dan masukkan ID paket, lalu klik Done.

  5. Klik Save untuk menyimpan perubahan dan kembali ke daftar kunci API.

gcloud

  1. Dapatkan ID kunci yang ingin Anda batasi.

    ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini dengan menggunakan perintah gcloud services api-keys list untuk menampilkan daftar kunci dalam project Anda.

  2. Gunakan metode gcloud beta services api-keys update untuk menentukan aplikasi iOS yang dapat menggunakan kunci tersebut.

    Ganti nilai berikut:

    • KEY_ID: ID kunci yang ingin Anda batasi.
    • ALLOWED_BUNDLE_ID: ID paket aplikasi iOS tempat Anda ingin dapat menggunakan kunci API ini.

      Anda dapat menambahkan ID paket sebanyak yang diperlukan; menggunakan koma untuk memisahkan ID.

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

Java

Untuk menjalankan contoh ini, Anda harus menginstal library klien 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

Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci 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. Dapatkan ID kunci yang ingin Anda batasi.

    ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini menggunakan metode keys.list. ID tercantum di kolom uid respons.

    Ganti PROJECT_ID dengan ID atau nama project Google Cloud Anda.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. Gunakan metode keys.patch untuk menentukan aplikasi iOS yang dapat menggunakan kunci API.

    Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mengetahui kapan operasi selesai dan mendapatkan status operasi.

    Ganti nilai berikut:

    • ALLOWED_BUNDLE_ID: ID paket aplikasi iOS yang dapat menggunakan kunci.

      Anda dapat menambahkan informasi untuk aplikasi sebanyak yang dibutuhkan; gunakan koma untuk memisahkan ID paket. Anda harus memberikan semua ID paket bersama permintaan; ID paket yang diberikan akan menggantikan aplikasi yang diizinkan pada kunci tersebut.

    • PROJECT_ID: Project ID atau nama project Google Cloud Anda.

    • KEY_ID: ID kunci yang ingin Anda batasi.

    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.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

Untuk informasi selengkapnya tentang menambahkan pembatasan aplikasi iOS ke kunci menggunakan REST API, lihat Menambahkan pembatasan iOS dalam dokumentasi API Keys API.

Menambahkan pembatasan API

Pembatasan API menentukan API mana yang dapat dipanggil menggunakan kunci API.

Untuk menambahkan pembatasan API, gunakan salah satu opsi berikut:

Konsol

  1. Di konsol Google Cloud, buka halaman Credentials.

    Buka Credentials

  2. Klik nama kunci API yang ingin Anda batasi.

  3. Di bagian API restrictions, klik Restrict key.

  4. Pilih semua API yang akan digunakan oleh kunci API Anda.

  5. Klik Save untuk menyimpan perubahan dan kembali ke daftar kunci API.

gcloud

  1. Dapatkan ID kunci yang ingin Anda batasi.

    ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini dengan menggunakan perintah gcloud services api-keys list untuk menampilkan daftar kunci dalam project Anda.

  2. Gunakan perintah gcloud beta services api-keys update untuk menentukan layanan mana yang dapat menggunakan kunci API untuk autentikasi.

    Ganti nilai berikut:

    • KEY_ID: ID kunci yang ingin Anda batasi.
    • SERVICE_1, SERVICE_2...: Nama layanan API yang dapat digunakan oleh kunci untuk diakses.

      Anda harus memberikan semua nama layanan dengan perintah update; nama layanan yang diberikan menggantikan layanan yang ada pada kunci tersebut.

    Anda dapat menemukan nama layanan dengan menelusuri API di dasbor API. Nama layanan berupa string seperti bigquery.googleapis.com.

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

Java

Untuk menjalankan contoh ini, Anda harus menginstal library klien 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

Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci 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. Dapatkan ID kunci yang ingin Anda batasi.

    ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini menggunakan metode keys.list. ID tercantum di kolom uid respons.

    Ganti PROJECT_ID dengan ID atau nama project Google Cloud Anda.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. Gunakan metode keys.patch untuk menetapkan layanan mana yang dapat menggunakan kunci API untuk autentikasi.

    Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mengetahui kapan operasi selesai dan mendapatkan status operasi.

    Ganti nilai berikut:

    • SERVICE_1, SERVICE_2...: Nama layanan API yang dapat digunakan oleh kunci untuk diakses.

      Anda harus memasukkan semua nama layanan dalam permintaan; nama layanan yang diberikan menggantikan layanan yang ada pada kunci tersebut.

      Anda dapat menemukan nama layanan dengan menelusuri API di dasbor API. Nama layanan berupa string seperti bigquery.googleapis.com.

    • PROJECT_ID: Project ID atau nama project Google Cloud Anda.

    • KEY_ID: ID kunci yang ingin Anda batasi.

    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.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

Untuk informasi selengkapnya tentang menambahkan pembatasan API ke kunci menggunakan REST API, lihat Menambahkan pembatasan API dalam dokumentasi API Keys API.

Mendapatkan informasi proyek dari string kunci

Anda dapat menentukan project Google Cloud mana yang terkait dengan kunci API dari string-nya.

Ganti KEY_STRING dengan string kunci yang informasi project Anda diperlukan.

gcloud

Gunakan perintah gcloud beta services api-keys lookup untuk mendapatkan project ID dari string kunci.

 gcloud beta services api-keys lookup KEY_STRING
 

Java

Untuk menjalankan contoh ini, Anda harus menginstal library klien 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

Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci 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

Gunakan metode lookupKey untuk mendapatkan project ID dari string kunci.

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

Membatalkan Penghapusan kunci API

Jika tidak sengaja menghapus kunci API, Anda dapat membatalkan penghapusan (memulihkan) kunci tersebut dalam waktu 30 hari setelah menghapus kunci. Setelah 30 hari, Anda tidak dapat membatalkan penghapusan kunci API.

Konsol

  1. Di konsol Google Cloud, buka halaman Credentials.

    Buka Credentials

  2. Klik Restore deleted credentials.

  3. Temukan kunci API yang dihapus yang ingin Anda batalkan penghapusannya, lalu klik Restore.

    Membatalkan penghapusan kunci API mungkin memerlukan waktu beberapa menit untuk diterapkan. Setelah penerapan, kunci API yang batal dihapus akan ditampilkan di daftar kunci API.

gcloud

  1. Dapatkan ID kunci yang ingin Anda batalkan penghapusannya.

    ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini dengan menggunakan perintah gcloud services api-keys list --show-deleted untuk mencantumkan kunci yang dihapus di project Anda.

  2. Gunakan perintah gcloud beta services api-keys undelete untuk membatalkan penghapusan kunci API.

    gcloud beta services api-keys undelete KEY_ID
    

    Ganti nilai berikut:

    • KEY_ID: ID kunci yang ingin Anda batalkan penghapusannya.

REST

  1. Dapatkan ID kunci yang ingin Anda batalkan penghapusannya.

    ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini menggunakan metode keys.list, dengan parameter kueri showDeleted ditetapkan ke true. ID kunci tercantum di kolom uid respons.

    Ganti PROJECT_ID dengan ID atau nama project Google Cloud Anda.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys?showDeleted=true"
    
  2. Gunakan metode undelete untuk membatalkan penghapusan kunci API.

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

    Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mengetahui kapan operasi selesai dan mendapatkan status operasi.

    Ganti nilai berikut:

    • PROJECT_ID: Project ID atau nama project Google Cloud Anda.
    • KEY_ID: ID kunci yang ingin Anda batasi.

Melakukan polling operasi yang berjalan lama

Metode API Keys API menggunakan operasi yang berjalan lama. Jika Anda menggunakan REST API untuk membuat dan mengelola kunci API, objek operasi akan ditampilkan dari permintaan metode awal. Anda menggunakan nama operasi untuk mengumpulkan operasi yang berjalan lama. Setelah permintaan yang berjalan lama selesai, polling operasi akan menampilkan data dari permintaan yang berjalan lama.

Untuk melakukan polling operasi API Keys API yang berjalan lama, gunakan metode operations.get.

Ganti OPERATION_NAME dengan nama operasi yang ditampilkan oleh operasi yang berjalan lama. Contoh, 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.googleapis.com/v2/OPERATION_NAME"

Batasan pada kunci API

Anda dapat membuat hingga 300 kunci API per project. Batas ini adalah batas sistem, dan tidak dapat diubah menggunakan permintaan penambahan kuota.

Jika diperlukan lebih dari satu kunci API, Anda harus menggunakan lebih dari satu project.

Langkah selanjutnya