Mengautentikasi workload dengan library autentikasi Google Cloud

Dokumen ini menunjukkan cara menggunakan Workload Identity Federation dengan Google Cloud library autentikasi, yang dikenal sebagai library autentikasi, untuk mengautentikasi workload dari penyedia identitas pihak ketiga seperti AWS, Microsoft Azure, dan penyedia yang mendukung OpenID Connect (OIDC) atau SAML 2.0.

Workload Identity Federation memungkinkan aplikasi yang berjalan di luar Google Cloud mengakses Google Cloud resource tanpa menggunakan kunci akun layanan. Library autentikasi Google memungkinkan hal ini dengan menukarkan kredensial eksternal dengan berjangka pendek Google Cloud token akses.

Untuk autentikasi, Anda dapat memperoleh kredensial eksternal menggunakan metode berikut:

Sebelum memulai

  1. Mengaktifkan API yang diperlukan.

    Peran yang diperlukan untuk mengaktifkan API

    Untuk mengaktifkan API, Anda memerlukan izin serviceusage.services.enable. Jika Anda membuat project, kemungkinan Anda sudah memiliki izin ini melalui peran Pemilik (roles/owner). Jika tidak, Anda bisa mendapatkan izin ini melalui peran Admin Service Usage (roles/serviceusage.serviceUsageAdmin). Pelajari cara memberikan peran.

    Aktifkan API

  2. Konfigurasi Workload Identity Federation dengan penyedia identitas Anda.

Mengautentikasi menggunakan mekanisme kredensial standar

Untuk penyedia identitas pihak ketiga yang umumnya didukung, Anda dapat menggunakan Google Cloud kemampuan bawaan library autentikasi untuk mengautentikasi workload dengan membuat file konfigurasi kredensial. File ini memberikan informasi yang diperlukan agar library autentikasi dapat menggabungkan identitas dari penyedia eksternal.

File konfigurasi kredensial, yang biasanya dimuat menggunakan variabel lingkungan GOOGLE_APPLICATION_CREDENTIALS, dapat menginstruksikan library autentikasi untuk mendapatkan token subjek pihak ketiga menggunakan salah satu metode berikut:

  • Dari file: Library membaca token subjek dari file lokal. Proses terpisah harus memastikan file ini berisi token yang valid dan belum habis masa berlakunya.
  • Dari URL: Library mengambil token subjek dengan membuat permintaan ke endpoint URL lokal yang ditentukan.
  • Dari file yang dapat dieksekusi: Library menjalankan perintah yang dapat dieksekusi yang dikonfigurasi. Output standar dari file yang dapat dieksekusi diharapkan berisi token subjek.
  1. Buat file konfigurasi kredensial untuk penyedia tertentu:

  2. Gunakan file konfigurasi kredensial untuk melakukan autentikasi.

    Agar library klien Google Cloud dapat otomatis menemukan dan menggunakan file konfigurasi kredensial Anda, tetapkan variabel lingkungan GOOGLE_APPLICATION_CREDENTIALS ke jalur file JSON yang dihasilkan.

    Ekspor variabel lingkungan di shell Anda: bash export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/config.json

    Setelah Anda menetapkan variabel lingkungan, library klien akan menangani alur autentikasi.

Contoh kode berikut menunjukkan cara melakukan panggilan yang diautentikasi ke Google Cloud API:

Node.js

Untuk mempelajari cara menginstal dan menggunakan library klien untuk IAM, lihat library klien IAM. Untuk informasi selengkapnya, lihat dokumentasi referensi API Node.js IAM.

Untuk melakukan autentikasi ke IAM, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

// Imports the Google Cloud client library.
const {Storage} = require('@google-cloud/storage');

// Instantiates a client. If you don't specify credentials when constructing
// the client, the client library will look for credentials in the
// environment.
const storage = new Storage();
// Makes an authenticated API request.
async function listBuckets() {
  try {
    const results = await storage.getBuckets();

    const [buckets] = results;

    console.log('Buckets:');
    buckets.forEach(bucket => {
      console.log(bucket.name);
    });
  } catch (err) {
    console.error('ERROR:', err);
  }
}
listBuckets();

Python

Untuk mempelajari cara menginstal dan menggunakan library klien untuk IAM, lihat library klien IAM. Untuk informasi selengkapnya, lihat dokumentasi referensi API Python IAM.

Untuk melakukan autentikasi ke IAM, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

def implicit():
    from google.cloud import storage

    # If you don't specify credentials when constructing the client, the
    # client library will look for credentials in the environment.
    storage_client = storage.Client()

    # Make an authenticated API request
    buckets = list(storage_client.list_buckets())
    print(buckets)

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk IAM, lihat library klien IAM. Untuk informasi selengkapnya, lihat dokumentasi referensi API Java IAM.

Untuk melakukan autentikasi ke IAM, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

static void authImplicit() {
  // If you don't specify credentials when constructing the client, the client library will
  // look for credentials via the environment variable GOOGLE_APPLICATION_CREDENTIALS.
  Storage storage = StorageOptions.getDefaultInstance().getService();

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

Go

Untuk mempelajari cara menginstal dan menggunakan library klien untuk IAM, lihat library klien IAM. Untuk informasi selengkapnya, lihat dokumentasi referensi API Go IAM.

Untuk melakukan autentikasi ke IAM, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import (
	"context"
	"fmt"
	"io"

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

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

	ctx := context.Background()

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

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

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

	return nil
}

Mengautentikasi menggunakan pemasok kredensial kustom

Jika lingkungan Anda tidak mendukung kemampuan bawaan library autentikasi Google atau jika Anda ingin menerapkan logika kustom untuk menyediakan kredensial ke library autentikasi Google, gunakan pemasok kredensial kustom untuk mengautentikasi workload Anda.

Mengakses resource dari AWS

Saat Anda menginisialisasi klien autentikasi, berikan implementasi kustom pemasok kredensial. Instance klien akan menangguhkan pemasok untuk mengambil kredensial keamanan AWS untuk ditukar dengan Google Cloud token akses. Pemasok harus menampilkan kredensial yang valid dan belum habis masa berlakunya saat klien memanggilnya.

Klien autentikasi tidak menyimpan kredensial keamanan atau region AWS yang ditampilkan dalam cache, jadi terapkan penyimpanan dalam cache di pemasok untuk mencegah permintaan berulang untuk resource yang sama.

Contoh kode berikut menunjukkan cara menyiapkan akses ke Google Cloud resource dari AWS dengan pemasok kredensial kustom.

Node.js

Untuk mempelajari cara menginstal dan menggunakan library klien untuk IAM, lihat library klien IAM. Untuk informasi selengkapnya, lihat dokumentasi referensi API Node.js IAM.

Untuk melakukan autentikasi ke IAM, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

const {AwsClient} = require('google-auth-library');
const {fromNodeProviderChain} = require('@aws-sdk/credential-providers');
const fs = require('fs');
const path = require('path');
const {STSClient} = require('@aws-sdk/client-sts');
const {Storage} = require('@google-cloud/storage');

/**
 * Custom AWS Security Credentials Supplier.
 *
 * This implementation resolves AWS credentials using the default Node provider
 * chain from the AWS SDK. This allows fetching credentials from environment
 * variables, shared credential files (~/.aws/credentials), or IAM roles
 * for service accounts (IRSA) in EKS, etc.
 */
class CustomAwsSupplier {
  constructor() {
    this.region = null;

    this.awsCredentialsProvider = fromNodeProviderChain();
  }

  /**
   * Returns the AWS region. This is required for signing the AWS request.
   * It resolves the region automatically by using the default AWS region
   * provider chain, which searches for the region in the standard locations
   * (environment variables, AWS config file, etc.).
   */
  async getAwsRegion(_context) {
    if (this.region) {
      return this.region;
    }

    const client = new STSClient({});
    this.region = await client.config.region();

    if (!this.region) {
      throw new Error(
        'CustomAwsSupplier: Unable to resolve AWS region. Please set the AWS_REGION environment variable or configure it in your ~/.aws/config file.'
      );
    }

    return this.region;
  }

  /**
   * Retrieves AWS security credentials using the AWS SDK's default provider chain.
   */
  async getAwsSecurityCredentials(_context) {
    const awsCredentials = await this.awsCredentialsProvider();

    if (!awsCredentials.accessKeyId || !awsCredentials.secretAccessKey) {
      throw new Error(
        'Unable to resolve AWS credentials from the node provider chain. ' +
          'Ensure your AWS CLI is configured, or AWS environment variables (like AWS_ACCESS_KEY_ID) are set.'
      );
    }

    return {
      accessKeyId: awsCredentials.accessKeyId,
      secretAccessKey: awsCredentials.secretAccessKey,
      token: awsCredentials.sessionToken,
    };
  }
}

/**
 * Authenticates with Google Cloud using AWS credentials and retrieves bucket metadata.
 *
 * @param {string} bucketName The name of the bucket to retrieve.
 * @param {string} audience The Workload Identity Pool audience.
 * @param {string} [impersonationUrl] Optional Service Account impersonation URL.
 */
async function authenticateWithAwsCredentials(
  bucketName,
  audience,
  impersonationUrl
) {
  const customSupplier = new CustomAwsSupplier();

  const clientOptions = {
    audience: audience,
    subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request',
    service_account_impersonation_url: impersonationUrl,
    aws_security_credentials_supplier: customSupplier,
  };

  const authClient = new AwsClient(clientOptions);

  const storage = new Storage({
    authClient: authClient,
  });

  const [metadata] = await storage.bucket(bucketName).getMetadata();
  return metadata;
}

Python

Untuk mempelajari cara menginstal dan menggunakan library klien untuk IAM, lihat library klien IAM. Untuk informasi selengkapnya, lihat dokumentasi referensi API Python IAM.

Untuk melakukan autentikasi ke IAM, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import json
import os
import sys

import boto3
from google.auth import aws
from google.auth import exceptions
from google.cloud import storage


class CustomAwsSupplier(aws.AwsSecurityCredentialsSupplier):
    """Custom AWS Security Credentials Supplier using Boto3."""

    def __init__(self):
        """Initializes the Boto3 session, prioritizing environment variables for region."""
        # Explicitly read the region from the environment first.
        region = os.getenv("AWS_REGION") or os.getenv("AWS_DEFAULT_REGION")

        # If region is None, Boto3's discovery chain will be used when needed.
        self.session = boto3.Session(region_name=region)
        self._cached_region = None

    def get_aws_region(self, context, request) -> str:
        """Returns the AWS region using Boto3's default provider chain."""
        if self._cached_region:
            return self._cached_region

        self._cached_region = self.session.region_name

        if not self._cached_region:
            raise exceptions.GoogleAuthError(
                "Boto3 was unable to resolve an AWS region."
            )

        return self._cached_region

    def get_aws_security_credentials(
        self, context, request=None
    ) -> aws.AwsSecurityCredentials:
        """Retrieves AWS security credentials using Boto3's default provider chain."""
        creds = self.session.get_credentials()
        if not creds:
            raise exceptions.GoogleAuthError(
                "Unable to resolve AWS credentials from Boto3."
            )

        return aws.AwsSecurityCredentials(
            access_key_id=creds.access_key,
            secret_access_key=creds.secret_key,
            session_token=creds.token,
        )


def authenticate_with_aws_credentials(bucket_name, audience, impersonation_url=None):
    """Authenticates using the custom AWS supplier and gets bucket metadata.

    Returns:
        dict: The bucket metadata response from the Google Cloud Storage API.
    """

    custom_supplier = CustomAwsSupplier()

    credentials = aws.Credentials(
        audience=audience,
        subject_token_type="urn:ietf:params:aws:token-type:aws4_request",
        service_account_impersonation_url=impersonation_url,
        aws_security_credentials_supplier=custom_supplier,
        scopes=["https://www.googleapis.com/auth/devstorage.read_only"],
    )

    storage_client = storage.Client(credentials=credentials)

    bucket = storage_client.get_bucket(bucket_name)

    return bucket._properties

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk IAM, lihat library klien IAM. Untuk informasi selengkapnya, lihat