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
搭配用戶端程式庫使用 API 金鑰
您只能搭配接受 API 金鑰的 API 用戶端程式庫使用 API 金鑰。此外,API 金鑰不得設有 API 限制,導致無法用於 API。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-08-19 (世界標準時間)。"],[[["\u003cp\u003eClient libraries simplify accessing Google Cloud APIs by handling tasks like authentication and reducing the amount of code needed, especially with Application Default Credentials (ADC).\u003c/p\u003e\n"],["\u003cp\u003eTo use ADC, you must set it up for your environment, which the client library will automatically utilize for authentication without needing explicit token management.\u003c/p\u003e\n"],["\u003cp\u003eAPI keys can be used with certain client libraries and APIs, but they need to be managed securely to prevent unauthorized access and unexpected charges.\u003c/p\u003e\n"],["\u003cp\u003eWhen accepting credential configurations from external sources, it is important to validate them thoroughly to prevent security compromises, particularly by confirming specific fields like the \u003ccode\u003etype\u003c/code\u003e and checking if \u003ccode\u003eservice_account\u003c/code\u003e or other URL values are correct.\u003c/p\u003e\n"],["\u003cp\u003eService account keys can be validated using credential loader specific to them, otherwise, the 'type' field should be verified to ensure it is set to \u003ccode\u003eservice_account\u003c/code\u003e.\u003c/p\u003e\n"]]],[],null,[]]