이 페이지에서는 클라이언트 라이브러리와 애플리케이션 기본 사용자 인증 정보를 사용하여 Google API에 액세스하는 방법을 설명합니다.
클라이언트 라이브러리를 사용하면 지원되는 언어로 Google Cloud API에 쉽게 액세스할 수 있습니다. 서버에 원시 요청을 수행해서 Google Cloud API를 직접 사용할 수 있지만 클라이언트 라이브러리는 작성할 코드 양을 크게 줄여 주는 간소화 기능을 제공합니다. 이는 클라이언트 라이브러리가 애플리케이션 기본 사용자 인증 정보(ADC)를 지원하기 때문에 특히 더 그렇습니다.
애플리케이션 기본 사용자 인증 정보를 사용하여 애플리케이션을 인증하려면 먼저 애플리케이션이 실행되는 환경에 대한 ADC를 설정해야 합니다. 클라이언트 라이브러리를 사용하여 클라이언트를 만드는 경우 클라이언트 라이브러리는 코드가 사용하는 API에 인증하기 위해 ADC에 제공된 사용자 인증 정보를 자동으로 확인하고 사용합니다. 애플리케이션이 토큰을 명시적으로 인증하거나 관리할 필요가 없습니다. 이러한 요구사항은 인증 라이브러리에 의해 자동으로 관리됩니다.
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,"Listedallstoragebuckets.\n")returnnil}
자바
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("Listedallstoragebuckets.");}}
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('Listedallstoragebuckets.');}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"):
"""
WheninteractingwithGoogleCloudClientlibraries,thelibrarycanauto-detectthecredentialstouse.//TODO(Developer)://1.Beforerunningthissample,//setupADCasdescribedinhttps://cloud.google.com/docs/authentication/external/set-up-adc//2.Replacetheprojectvariable.//3.Makesurethattheuseraccountorserviceaccountthatyouareusing//hastherequiredpermissions.Forthissample,youmusthave "storage.buckets.list".Args:project_id:TheprojectidofyourGoogleCloudproject.
"""
# 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("Listedallstoragebuckets.")
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:Listedallstoragebuckets."
end