이 페이지에서는 클라이언트 라이브러리를 사용하여 Google API에 액세스하는 방법을 설명합니다.
클라이언트 라이브러리를 사용하면 지원되는 언어로 Cloud de Confiance by S3NS API에 쉽게 액세스할 수 있습니다. 원시 요청을 서버에 보내 Cloud de Confiance by S3NS API를 직접 사용할 수 있지만 클라이언트 라이브러리는 작성해야 하는 코드 양을 크게 줄여 주는 간소화 기능을 제공합니다. 이는 클라이언트 라이브러리가 애플리케이션 기본 사용자 인증 정보(ADC)를 지원하기 때문에 특히 더 그렇습니다.
애플리케이션 기본 사용자 인증 정보를 사용하여 애플리케이션을 인증하려면 먼저 애플리케이션이 실행되는 환경에 대한 ADC를 설정해야 합니다. 클라이언트 라이브러리를 사용하여 클라이언트를 만드는 경우 클라이언트 라이브러리는 코드가 사용하는 API에 인증하기 위해 ADC에 제공된 사용자 인증 정보를 자동으로 확인하고 사용합니다. 애플리케이션이 토큰을 명시적으로 인증하거나 관리할 필요가 없습니다. 이러한 요구사항은 인증 라이브러리에 의해 자동으로 관리됩니다.
GOOGLE_CLOUD_UNIVERSE_DOMAIN 환경 변수를 s3nsapis.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}
자바
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 제한사항이 없어야 합니다.
애플리케이션에서 API 키를 사용하는 경우 저장 및 전송 중에 안전하게 보호되도록 해야 합니다. API 키를 공개적으로 노출하면 계정에 예상치 않은 비용이 부과될 수 있습니다. 자세한 내용은 API 키 관리 권장사항을 참조하세요.
외부 소스 사용자 인증 정보 구성을 사용할 때의 보안 요구사항
일반적으로 gcloud CLI 명령어를 사용하거나 Cloud de Confiance 콘솔을 사용하여 사용자 인증 정보 구성을 생성합니다. 예를 들어 gcloud CLI를 사용하여 로컬 ADC 파일이나 로그인 구성 파일을 생성할 수 있습니다. 마찬가지로 Cloud de Confiance 콘솔을 사용하여 서비스 계정 키를 만들고 다운로드할 수 있습니다.
그러나 일부 사용 사례에서는 외부 법인이 사용자 인증 정보 구성을 제공합니다. 이러한 사용자 인증 정보 구성은 Google 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-11-11(UTC)"],[],[]]