Panduan memulai: Mengamankan traffic ke layanan dengan gcloud CLI

Halaman ini menunjukkan cara men-deploy API di API Gateway untuk mengamankan traffic ke layanan backend.

Gunakan langkah-langkah berikut untuk men-deploy API baru guna mengakses layanan backend di fungsi Cloud Run menggunakan Google Cloud CLI. Panduan memulai ini juga menjelaskan cara menggunakan kunci API untuk melindungi backend Anda dari akses yang tidak sah.

Sebelum memulai

  1. Di konsol Google Cloud , buka halaman Dasbor, lalu pilih atau buat project Google Cloud .

    Buka Dasbor

  2. Konfirmasi bahwa penagihan diaktifkan untuk project Anda.

    Mengaktifkan penagihan

  3. Pastikan Google Cloud CLI telah didownload dan diinstal di komputer Anda.

    Download gcloud CLI

  4. Perbarui komponen gcloud:

    gcloud components update
  5. Tetapkan project default. Ganti PROJECT_ID dengan project ID Google Cloud Anda.

    gcloud config set project PROJECT_ID

Mengaktifkan layanan yang diperlukan

Gateway API mengharuskan Anda mengaktifkan layanan Google berikut:

Nama Judul
apigateway.googleapis.com API Gateway API
servicemanagement.googleapis.com Service Management API
servicecontrol.googleapis.com Service Control API

Gunakan perintah berikut untuk mengaktifkan layanan ini:

gcloud services enable apigateway.googleapis.com
gcloud services enable servicemanagement.googleapis.com
gcloud services enable servicecontrol.googleapis.com

Untuk mengetahui informasi selengkapnya tentang layanan gcloud, lihat Layanan gcloud.

Men-deploy backend API

Gateway API berada di depan layanan backend yang di-deploy dan menangani semua permintaan masuk. Dalam panduan memulai ini, API Gateway merutekan panggilan masuk ke backend fungsi Cloud Run bernama helloGET yang berisi fungsi berikut:

/**
 * HTTP Cloud Function.
 * This function is exported by index.js, and is executed when
 * you make an HTTP request to the deployed function's endpoint.
 *
 * @param {Object} req Cloud Function request context.
 *                     More info: https://expressjs.com/en/api.html#req
 * @param {Object} res Cloud Function response context.
 *                     More info: https://expressjs.com/en/api.html#res
 */

exports.helloGET = (req, res) => {
  res.send('Hello World!');
};

Ikuti langkah-langkah di Panduan memulai: Menggunakan Google Cloud CLI untuk mendownload kode fungsi Cloud Run contoh dan men-deploy layanan backend fungsi Cloud Run.

Membuat API

Sekarang Anda siap membuat API di API Gateway.

  1. Masukkan perintah berikut, dengan:

    • API_ID menentukan nama API Anda. Lihat persyaratan ID API untuk mengetahui pedoman penamaan API.
      gcloud api-gateway apis create API_ID 

    Contoh:

    gcloud api-gateway apis create my-api
  2. Setelah berhasil diselesaikan, Anda dapat menggunakan perintah berikut untuk melihat detail tentang API baru:

    gcloud api-gateway apis describe API_ID 

    Contoh:

    gcloud api-gateway apis describe my-api 

    Perintah ini menampilkan hal berikut:

      createTime: '2020-02-29T21:52:20.297426875Z'
      displayName: my-api
      managedService: my-api-123abc456def1.apigateway.my-project.cloud.goog
      name: projects/my-project/locations/global/apis/my-api
      state: ACTIVE
      updateTime: '2020-02-29T21:52:20.647923711Z'

Perhatikan nilai properti managedService. Nilai ini digunakan untuk mengaktifkan API Anda pada langkah berikutnya.

Membuat konfigurasi API

Sebelum API Gateway dapat digunakan untuk mengelola traffic ke backend API yang di-deploy, API Gateway memerlukan konfigurasi API.

Anda dapat membuat konfigurasi API menggunakan deskripsi OpenAPI yang berisi anotasi khusus untuk menentukan perilaku API Gateway yang dipilih. Untuk mengetahui detail selengkapnya tentang ekstensi OpenAPI yang didukung, lihat artikel berikut:

Deskripsi OpenAPI yang digunakan untuk panduan memulai ini berisi petunjuk perutean ke backend fungsi Cloud Run kami:

OpenAPI 2.0

# openapi-functions.yaml
swagger: '2.0'
info:
  title: API_ID optional-string
  description: Sample API on API Gateway with a Google Cloud Functions backend
  version: 1.0.0
schemes:
  - https
produces:
  - application/json
paths:
  /hello:
    get:
      summary: Greet a user
      operationId: hello
      x-google-backend:
        address: https://GATEWAY_LOCATION-PROJECT_ID.cloudfunctions.net/helloGET
      responses:
        '200':
          description: A successful response
          schema:
            type: string

OpenAPI 3.x

# openapi-functions.yaml
openapi: 3.0.4
info:
  title: API_ID optional-string
  description: Sample API on API Gateway with a Google Cloud Functions backend
  version: 1.0.0
# Define reusable components in x-google-api-management
x-google-api-management:
  backend:
    functions_backend:
      address: https://GATEWAY_LOCATION-PROJECT_ID.cloudfunctions.net/helloGET
      pathTranslation: APPEND_PATH_TO_ADDRESS
      protocol: "http/1.1"
# Apply the backend configuration by referencing it by name. Set at the root so this applies to all operations unless overridden.
x-google-backend: functions_backend
paths:
  /hello:
    get:
      summary: Greet a user
      operationId: hello
      responses:
        '200':
          description: A successful response
          content:
            application/json:
              schema:
                type: string

Untuk mengupload deskripsi OpenAPI ini dan membuat konfigurasi API menggunakan gcloud CLI:

  1. Dari command line, buat file baru bernama openapi-functions.yaml.

  2. Salin dan tempel konten deskripsi OpenAPI ke dalam file yang baru dibuat.

  3. Edit file sebagai berikut:

    1. Di kolom title, ganti API_ID dengan nama API Anda dan ganti optional-string dengan deskripsi singkat pilihan Anda. Nilai kolom ini digunakan saat membuat kunci API yang memberikan akses ke API ini.
    2. Di kolom address, ganti GATEWAY_LOCATION dengan region Google Cloud fungsi yang di-deploy dan PROJECT_ID dengan nama project Google Cloud Anda.
  4. Masukkan perintah berikut, dengan:

    • CONFIG_ID menentukan nama konfigurasi API Anda.
    • API_ID menentukan nama API Anda.
    • API_DEFINITION menentukan nama file spesifikasi OpenAPI.
    • SERVICE_ACCOUNT_EMAIL menentukan akun layanan yang digunakan untuk menandatangani token untuk backend dengan autentikasi yang dikonfigurasi. Untuk mengetahui informasi selengkapnya, lihat Mengonfigurasi akun layanan.
    gcloud api-gateway api-configs create CONFIG_ID \
      --api=API_ID --openapi-spec=API_DEFINITION \
       --backend-auth-service-account=SERVICE_ACCOUNT_EMAIL

    Contoh:

    gcloud api-gateway api-configs create my-config \
      --api=my-api --openapi-spec=openapi2-functions.yaml \
      --backend-auth-service-account=0000000000000-compute@developer.gserviceaccount.com

    Operasi ini mungkin memerlukan waktu beberapa menit untuk selesai karena konfigurasi API disebarkan ke sistem hilir. Membuat konfigurasi API yang kompleks dapat memerlukan waktu hingga sepuluh menit agar berhasil diselesaikan.

  5. Setelah konfigurasi API dibuat, Anda dapat melihat detailnya dengan menjalankan perintah ini:

    gcloud api-gateway api-configs describe CONFIG_ID \
      --api=API_ID 

    Contoh:

    gcloud api-gateway api-configs describe my-config \
      --api=my-api

    Output menampilkan detail konfigurasi API Anda, termasuk nama dan status, seperti yang ditunjukkan dalam contoh berikut:

    createTime: '2020-02-07T18:17:01.839180746Z'
    displayName: my-config
    gatewayConfig:
    backendConfig:
      googleServiceAccount: 0000000000000-compute@developer.gserviceaccount.com
    name: projects/my-project/locations/global/apis/my-api/configs/my-config
    serviceRollout:
    rolloutId: 2020-02-07r0
    state: ACTIVE
    updateTime: '2020-02-07T18:17:02.173778118Z'

Membuat gateway

Sekarang deploy konfigurasi API di gateway. Men-deploy konfigurasi API di gateway menentukan URL eksternal yang dapat digunakan klien API untuk mengakses API Anda.

Jalankan perintah berikut untuk men-deploy konfigurasi API yang baru saja Anda buat ke API Gateway:

gcloud api-gateway gateways create GATEWAY_ID \
  --api=API_ID --api-config=CONFIG_ID \
  --location=GCP_REGION 

dengan:

  • GATEWAY_ID menentukan nama gateway.
  • API_ID menentukan nama API Gateway API yang terkait dengan gateway ini.
  • CONFIG_ID menentukan nama konfigurasi API yang di-deploy ke gateway.
  • GCP_REGION adalah Google Cloud region untuk gateway yang di-deploy.

  • PROJECT_ID menentukan nama project Google Cloud Anda.

Contoh:

gcloud api-gateway gateways create my-gateway \
  --api=my-api --api-config=my-config \
  --location=us-central1 

Setelah berhasil diselesaikan, gunakan perintah berikut untuk melihat detail tentang gateway:

gcloud api-gateway gateways describe GATEWAY_ID \
  --location=GCP_REGION 

Contoh:

gcloud api-gateway gateways describe my-gateway \
  --location=us-central1 

Perintah ini menampilkan hal berikut:

apiConfig: projects/my-project/locations/global/apis/my-api/configs/my-config
createTime: '2020-02-05T13:44:12.997862831Z'
defaultHostname: my-gateway-a12bcd345e67f89g0h.uc.gateway.dev
displayName: my-gateway
name: projects/my-project/locations/us-central1/gateways/my-gateway
serviceAccount:
      email: 0000000000000-compute@developer.gserviceaccount.com
state: ACTIVE
updateTime: '2020-02-05T13:45:00.844705087Z'

Perhatikan nilai properti defaultHostname. Ini adalah bagian nama host dari URL gateway yang Anda gunakan untuk menguji deployment pada langkah berikutnya.

Menguji deployment API Anda

Sekarang Anda dapat mengirim permintaan ke API Anda menggunakan URL yang dihasilkan saat deployment gateway Anda.

Masukkan perintah curl berikut, dengan:

  • DEFAULT_HOSTNAME menentukan bagian nama host dari URL gateway yang di-deploy.
  • hello adalah jalur yang ditentukan dalam konfigurasi API Anda.
curl https://DEFAULT_HOSTNAME/hello

Contoh:

curl https://my-gateway-a12bcd345e67f89g0h.uc.gateway.dev/hello

Outputnya adalah:

Hello World!

Anda telah berhasil membuat dan men-deploy Gateway API.

Mengamankan akses menggunakan kunci API

Untuk mengamankan akses ke backend API Anda, buat kunci API yang terkait dengan project Anda dan berikan akses kunci tersebut untuk memanggil API Anda. Lihat Membatasi akses API dengan kunci API untuk mengetahui informasi selengkapnya.

Jika belum memiliki kunci API yang terkait dengan Google Cloud project yang Anda gunakan dalam panduan memulai ini, Anda dapat menambahkannya dengan mengikuti langkah-langkah di Membuat Kunci API.

Untuk mengamankan akses ke gateway menggunakan kunci API:

  1. Aktifkan dukungan kunci API untuk layanan Anda. Masukkan perintah berikut, dengan:
    • MANAGED_SERVICE_NAME menentukan nama layanan terkelola yang dibuat saat Anda men-deploy API. Hal ini dapat dilihat di properti Managed Service yang tercantum dengan perintah gcloud apigee-gateway apis describe.
    • PROJECT_ID menentukan nama project Google Cloud Anda.
    gcloud services enable MANAGED_SERVICE_NAME.apigateway.PROJECT_ID.cloud.goog
    Contoh:
    gcloud services enable my-api-123abc456def1.apigateway.my-project.cloud.goog
  2. Ubah deskripsi OpenAPI yang digunakan untuk membuat konfigurasi API Anda agar menyertakan petunjuk untuk menerapkan kebijakan keamanan validasi kunci API pada semua traffic. Tambahkan jenis security dan securityDefinitions seperti yang ditunjukkan:

    OpenAPI 2.0

      # openapi2-functions.yaml
      swagger: '2.0'
      info:
        title: API_ID optional-string
        description: Sample API on API Gateway with a Google Cloud Functions backend
        version: 1.0.0
      schemes:
        - https
      produces:
        - application/json
      paths:
        /hello:
          get:
            summary: Greet a user
            operationId: hello
            x-google-backend:
              address: https://GATEWAY_LOCATION-PROJECT_ID.cloudfunctions.net/helloGET
            security:
            - api_key: []
            responses:
              '200':
                description: A successful response
                schema:
                  type: string
      securityDefinitions:
        # This section configures basic authentication with an API key.
        api_key:
          type: "apiKey"
          name: "key"
          in: "query"
    securityDefinition mengonfigurasi API Anda agar memerlukan kunci API yang diteruskan sebagai parameter kueri bernama key saat meminta akses ke semua jalur yang ditentukan dalam spesifikasi.

    OpenAPI 3.x

    # openapi-functions.yaml
    openapi: 3.0.4
    info:
      title: API_ID optional-string
      description: Sample API on API Gateway with a Google Cloud Functions backend
      version: 1.0.0
    # Define reusable components in x-google-api-management
    x-google-api-management:
      backend:
        functions_backend:
          address: https://GATEWAY_LOCATION-PROJECT_ID.cloudfunctions.net/helloGET
          pathTranslation: APPEND_PATH_TO_ADDRESS
          protocol: "http/1.1"
    # Apply the backend configuration by referencing it by name. Set at the root so this applies to all operations unless overridden.
    x-google-backend: functions_backend
    components:
    # This section configures basic authentication with an API key.
      securitySchemes:
        google_api_key:
          type: apiKey
          name: x-api-key
          in: header
    security:
      - google_api_key: []
    paths:
      /hello:
        get:
          summary: Greet a user
          operationId: hello
          responses:
            '200':
              description: A successful response
              content:
                application/json:
                  schema:
                    type: string
    securitySchemes mengonfigurasi API Anda agar memerlukan kunci API yang diteruskan sebagai parameter kueri bernama key saat meminta akses ke semua jalur yang ditentukan dalam spesifikasi.
  3. Buat konfigurasi API baru dengan spesifikasi OpenAPI yang telah diubah menggunakan perintah berikut:
    gcloud api-gateway api-configs create NEW_CONFIG_ID \
    --api=API_ID --openapi-spec=NEW_API_DEFINITION \
    --backend-auth-service-account=SERVICE_ACCOUNT_EMAIL
    Contoh:
    gcloud api-gateway api-configs create my-config-key \
      --api=my-api --openapi-spec=openapi2-functions.yaml \
      --project=my-project --backend-auth-service-account=0000000000000compute@developer.gserviceaccount.com
  4. Jalankan perintah berikut untuk mengupdate gateway yang ada dengan konfigurasi API baru:
    gcloud api-gateway gateways update GATEWAY_ID \
      --api=API_ID --api-config=NEW_CONFIG_ID \
      --location=GCP_REGION 
    Contoh:
    gcloud api-gateway gateways update my-gateway \
      --api=my-api --api-config=my-config-key \
      --location=us-central1 

Menguji kunci API Anda

Setelah Anda membuat dan men-deploy API yang diubah, coba buat permintaan ke API tersebut.

Masukkan perintah curl berikut, dengan:

  • DEFAULT_HOSTNAME menentukan bagian nama host dari URL gateway yang di-deploy.
  • hello adalah jalur yang ditentukan dalam konfigurasi API Anda.
curl https://DEFAULT_HOSTNAME/hello

Contoh:

curl https://my-gateway-a12bcd345e67f89g0h.uc.gateway.dev/hello

Tindakan ini akan menghasilkan error berikut:

UNAUTHENTICATED:Method doesn't allow unregistered callers (callers without established identity). Please use API Key or other form of API consumer identity to call this API.

Sekarang, masukkan perintah curl berikut dengan:

  • DEFAULT_HOSTNAME menentukan bagian nama host dari URL gateway yang di-deploy.
  • hello adalah jalur yang ditentukan dalam konfigurasi API Anda.
  • API_KEY menentukan kunci API yang Anda buat di langkah sebelumnya.
curl https://DEFAULT_HOSTNAME/hello?key=API_KEY

Sekarang Anda akan melihat Hello World! dalam respons dari API Anda.

Selamat! Anda telah berhasil melindungi backend API dengan Gateway API. Sekarang Anda dapat mulai mengintegrasikan klien API baru dengan membuat kunci API tambahan.

Pembersihan

Agar akun Google Cloud Anda tidak dikenai biaya untuk resource yang digunakan dalam panduan memulai ini, Anda dapat:

Atau, Anda juga dapat menghapus project Google Cloud yang digunakan untuk tutorial ini.

Langkah berikutnya