Halaman ini menjelaskan cara menggunakan library klien untuk mengakses Google API.
Library klien mempermudah akses Trusted Cloud by S3NS API
menggunakan bahasa yang didukung. Anda dapat menggunakan Trusted Cloud by S3NS API secara langsung dengan
membuat permintaan mentah ke server, tetapi library klien memberikan penyederhanaan
yang secara signifikan mengurangi jumlah kode yang perlu Anda tulis. Hal ini
terutama berlaku untuk autentikasi, karena library klien mendukung
Kredensial Default Aplikasi (ADC).
Menggunakan Kredensial Default Aplikasi dengan library klien
Untuk menggunakan Kredensial Default Aplikasi guna mengautentikasi aplikasi, Anda
harus terlebih dahulu menyiapkan ADC untuk
lingkungan tempat aplikasi berjalan. Saat Anda menggunakan library klien untuk membuat klien, library klien akan otomatis memeriksa dan
menggunakan kredensial yang Anda berikan ke ADC untuk melakukanautentikasi ke API
yang digunakan oleh kode Anda. Aplikasi Anda tidak perlu secara eksplisit mengautentikasi
atau mengelola token; persyaratan ini dikelola secara otomatis oleh
library autentikasi.
Contoh kode berikut membuat klien untuk layanan Cloud Storage.
Kode Anda cenderung membutuhkan klien yang berbeda; contoh ini dimaksudkan hanya untuk
menunjukkan cara membuat klien dan menggunakannya tanpa kode untuk mengautentikasi secara
eksplisit.
Sebelum dapat menjalankan contoh berikut, Anda harus menyelesaikan langkah-langkah berikut:
Tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke
apis-s3ns.fr.
Go
import("context""fmt""io""cloud.google.com/go/storage""google.golang.org/api/iterator")// authenticateImplicitWithAdc uses Application Default Credentials// to automatically find credentials and authenticate.funcauthenticateImplicitWithAdc(wio.Writer,projectIdstring)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)iferr!=nil{returnfmt.Errorf("NewClient: %w",err)}deferclient.Close()it:=client.Buckets(ctx,projectId)for{bucketAttrs,err:=it.Next()iferr==iterator.Done{break}iferr!=nil{returnerr}fmt.Fprintf(w,"Bucket: %v\n",bucketAttrs.Name)}fmt.Fprintf(w,"Listed all storage buckets.\n")returnnil}
Java
importcom.google.api.gax.paging.Page;importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.io.IOException;publicclassAuthenticateImplicitWithAdc{publicstaticvoidmain(String[]args)throwsIOException{// TODO(Developer):// 1. Before running this sample,// set up Application Default Credentials as described in// https://cloud.google.com/docs/authentication/external/set-up-adc// 2. Replace the project variable below.// 3. Make sure you have the necessary permission to list storage buckets// "storage.buckets.list"StringprojectId="your-google-cloud-project-id";authenticateImplicitWithAdc(projectId);}// When interacting with Google Cloud Client libraries, the library can auto-detect the// credentials to use.publicstaticvoidauthenticateImplicitWithAdc(Stringproject)throwsIOException{// *NOTE*: Replace the client created below with the client required for your application.// Note that the credentials are not specified when constructing the client.// Hence, the client library will look for credentials using ADC.//// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests.Storagestorage=StorageOptions.newBuilder().setProjectId(project).build().getService();System.out.println("Buckets:");Page<Bucket>buckets=storage.list();for(Bucketbucket:buckets.iterateAll()){System.out.println(bucket.toString());}System.out.println("Listed all storage buckets.");}}
Node.js
/** * TODO(developer): * 1. Uncomment and replace these variables before running the sample. * 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 list storage buckets "storage.buckets.list" * (https://cloud.google.com/storage/docs/access-control/iam-permissions#bucket_permissions) */// const projectId = 'YOUR_PROJECT_ID';const{Storage}=require('@google-cloud/storage');asyncfunctionauthenticateImplicitWithAdc(){// This snippet demonstrates how to list buckets.// 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.conststorage=newStorage({projectId,});const[buckets]=awaitstorage.getBuckets();console.log('Buckets:');for(constbucketofbuckets){console.log(`- ${bucket.name}`);}console.log('Listed all storage buckets.');}authenticateImplicitWithAdc();
PHP
// Imports the Cloud Storage client library.use Google\Cloud\Storage\StorageClient;/** * Authenticate to a cloud client library using a service account implicitly. * * @param string $projectId The Google project ID. */function auth_cloud_implicit($projectId){ $config = [ 'projectId' => $projectId, ]; # If you don't specify credentials when constructing the client, the # client library will look for credentials in the environment. $storage = new StorageClient($config); # Make an authenticated API request (listing storage buckets) foreach ($storage->buckets() as $bucket) { printf('Bucket: %s' . PHP_EOL, $bucket->name()); }}
Python
fromgoogle.cloudimportstoragedefauthenticate_implicit_with_adc(project_id="your-google-cloud-project-id"):""" When interacting with Google Cloud Client libraries, the library can auto-detect the credentials to use. // TODO(Developer): // 1. Before running this sample, // set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc // 2. Replace the project variable. // 3. Make sure that the user account or service account that you are using // has the required permissions. For this sample, you must have "storage.buckets.list". Args: project_id: The project id of your Google Cloud project. """# This snippet demonstrates how to list buckets.# *NOTE*: Replace the client created below with the client required for your application.# Note that the credentials are not specified when constructing the client.# Hence, the client library will look for credentials using ADC.storage_client=storage.Client(project=project_id)buckets=storage_client.list_buckets()print("Buckets:")forbucketinbuckets:print(bucket.name)print("Listed all storage buckets.")
Ruby
defauthenticate_implicit_with_adcproject_id:# The ID of your Google Cloud project# project_id = "your-google-cloud-project-id"#### When interacting with Google Cloud Client libraries, the library can auto-detect the# credentials to use.# TODO(Developer):# 1. Before running this sample,# set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc# 2. Replace the project variable.# 3. Make sure that the user account or service account that you are using# has the required permissions. For this sample, you must have "storage.buckets.list".###require"google/cloud/storage"# This sample demonstrates how to list buckets.# *NOTE*: Replace the client created below with the client required for your application.# Note that the credentials are not specified when constructing the client.# Hence, the client library will look for credentials using ADC.storage=Google::Cloud::Storage.newproject_id:project_idbuckets=storage.bucketsputs"Buckets: "buckets.eachdo|bucket|putsbucket.nameendputs"Plaintext: Listed all storage buckets."end
Menggunakan kunci API dengan library klien
Anda hanya dapat menggunakan kunci API dengan library klien untuk API yang menerima kunci API. Selain itu, kunci API tidak boleh memiliki pembatasan API yang mencegahnya digunakan untuk API.
Untuk mengetahui informasi selengkapnya tentang kunci API yang dibuat dalam mode ekspres, lihat
FAQ mode ekspres Google Cloud.
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 mengetahui informasi selengkapnya, lihat
Praktik terbaik untuk mengelola kunci API.
Persyaratan keamanan saat menggunakan konfigurasi kredensial dari sumber eksternal
Biasanya, Anda membuat konfigurasi kredensial menggunakan perintah gcloud CLI atau menggunakan konsol Trusted Cloud . Misalnya, Anda dapat menggunakan
gcloud CLI untuk membuat file ADC lokal atau file konfigurasi
login. Demikian pula, Anda dapat menggunakan konsol Trusted Cloud untuk membuat dan mendownload
kunci akun layanan.
Namun, untuk beberapa kasus penggunaan, konfigurasi kredensial diberikan kepada Anda oleh entitas eksternal; konfigurasi kredensial ini dimaksudkan untuk digunakan guna melakukan autentikasi ke Google API.
Beberapa jenis konfigurasi kredensial mencakup endpoint dan jalur file, yang digunakan oleh library autentikasi untuk mendapatkan token. Saat menerima konfigurasi
kredensial dari sumber eksternal, Anda harus memvalidasi konfigurasi
sebelum menggunakannya. Jika Anda tidak memvalidasi konfigurasi, pelaku berbahaya
dapat menggunakan kredensial untuk membahayakan sistem dan data Anda.
Memvalidasi konfigurasi kredensial dari sumber eksternal
Cara Anda perlu memvalidasi kredensial eksternal bergantung pada jenis
kredensial yang diterima aplikasi Anda.
Memvalidasi kunci akun layanan
Jika aplikasi Anda hanya menerima kunci akun layanan, gunakan pemuat
kredensial khusus untuk kunci akun layanan, seperti yang ditunjukkan dalam contoh berikut. Pemuat kredensial khusus jenis hanya mengurai kolom yang ada untuk kunci akun layanan, yang tidak mengekspos kerentanan apa pun.
Jika Anda tidak dapat menggunakan pemuat kredensial khusus jenis, validasi kredensial dengan
mengonfirmasi bahwa nilai untuk kolom type adalah service_account. Jika nilai kolom type adalah nilai lain, jangan gunakan kunci akun layanan.
Tabel berikut mencantumkan kolom yang perlu Anda validasi, jika ada
dalam kredensial Anda. Tidak semua kolom ini ada untuk semua konfigurasi kredensial.
Kolom
Tujuan
Nilai yang diharapkan
service_account_impersonation_url
Library autentikasi menggunakan kolom ini untuk mengakses endpoint guna
membuat token akses untuk akun layanan yang identitasnya ditiru.
Library autentikasi mengirim token eksternal ke endpoint ini untuk
menukarnya dengan
token akses federasi.
https://sts.apis-s3ns.fr/v1/token
credential_source.file
Library autentikasi membaca token eksternal dari file di
lokasi yang ditentukan oleh kolom ini dan mengirimkannya ke
endpoint token_url.
Jalur untuk file yang berisi token eksternal. Anda harus
mengenali jalur ini.
credential_source.url
Endpoint yang menampilkan token eksternal. Library autentikasi
mengirim permintaan ke URL ini dan mengirim respons ke
endpoint token_url.
Salah satu item berikut:
Endpoint terkenal yang disediakan oleh penyedia cloud Anda.
Endpoint yang telah Anda siapkan secara eksplisit untuk menyediakan token.
credential_source.executable.command
Jika variabel lingkungan GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES
ditetapkan ke 1, library autentikasi
akan menjalankan perintah atau file yang dapat dieksekusi ini.
File atau perintah yang dapat dieksekusi yang menampilkan token eksternal.
Anda harus mengenali perintah ini dan memvalidasi bahwa perintah tersebut aman.
credential_source.aws.url
Library autentikasi mengirimkan permintaan ke URL ini untuk mengambil
token keamanan AWS.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Informasi yang saya butuhkan tidak ada","missingTheInformationINeed","thumb-down"],["Terlalu rumit/langkahnya terlalu banyak","tooComplicatedTooManySteps","thumb-down"],["Sudah usang","outOfDate","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Masalah kode / contoh","samplesCodeIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-08-19 UTC."],[[["Client libraries simplify accessing Google Cloud APIs by handling tasks like authentication and reducing the amount of code needed, especially with Application Default Credentials (ADC)."],["To use ADC, you must set it up for your environment, which the client library will automatically utilize for authentication without needing explicit token management."],["API keys can be used with certain client libraries and APIs, but they need to be managed securely to prevent unauthorized access and unexpected charges."],["When accepting credential configurations from external sources, it is important to validate them thoroughly to prevent security compromises, particularly by confirming specific fields like the `type` and checking if `service_account` or other URL values are correct."],["Service account keys can be validated using credential loader specific to them, otherwise, the 'type' field should be verified to ensure it is set to `service_account`."]]],[]]