בדף הזה נסביר איך להשתמש בספריות לקוח כדי לגשת ל-Google APIs.
ספריות לקוח מאפשרות לגשת בקלות ל-Cloud de Confiance by S3NS APIs בשפה נתמכת. אפשר להשתמש ישירות ב- Cloud de Confiance by S3NS APIs על ידי יצירת בקשות גולמיות חדשות לשרת, אבל ספריות לקוח מפשטות את התהליך ומפחיתות באופן משמעותי את כמות הקוד שתצטרכו לכתוב. זה נכון במיוחד לאימות, כי ספריות הלקוח תומכות ב-Application Default Credentials (ADC).
שימוש ב-Application Default Credentials עם ספריות לקוח
קודם כול צריך להגדיר את השירות Application Default Credentials בסביבה שבה האפליקציה פועלת, כדי שתוכלו להשתמש בו לאימות האפליקציה שלכם. לאחר מכן, כשיוצרים לקוח באמצעות ספריית הלקוח, היא מחפשת באופן אוטומטי את פרטי הכניסה שסיפקתם ל-ADC ומשתמשת בהם כדי לאמת את ממשקי ה-API שבהם הקוד שלכם משתמש. אין צורך לאמת ולנהל אסימונים באופן מפורש. הדרישות האלו מנוהלות אוטומטית על ידי ספריות האימות.
דוגמאות הקוד הבאות מדגימות יצירה של לקוח לשירות Cloud Storage.
סביר להניח שבקוד שלכם תשתמשו בלקוחות אחרים. הדוגמאות האלו נועדו רק כדי להמחיש איך יוצרים לקוח ומשתמשים בו ללא קוד שמבצע אימות באופן מפורש.
כדי להריץ את הדוגמאות הבאות, צריך לבצע את השלבים הבאים:
מגדירים את משתנה הסביבה 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}
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:str="your-google-cloud-project-id")-> None:""" 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.
דרישות אבטחה כשמשתמשים בהגדרות של פרטי כניסה ממקור חיצוני
בדרך כלל, יוצרים הגדרות של פרטי כניסה באמצעות פקודות של ה-CLI של gcloud או באמצעות Cloud de Confiance המסוף. לדוגמה, אפשר להשתמש ב-CLI של gcloud כדי ליצור קובץ ADC מקומי או קובץ הגדרות כניסה. באופן דומה, אפשר להשתמש במסוף Cloud de Confiance כדי ליצור מפתח של חשבון שירות ולהוריד אותו.
עם זאת, בחלק ממקרי השימוש, ישויות חיצוניות מספקות לכם הגדרות של פרטי כניסה, וההגדרות האלה מיועדות לאימות מול Google APIs.
חלק מהסוגים של הגדרות פרטי כניסה כוללים נקודות קצה ונתיבי קבצים, שספריות האימות משתמשות בהם כדי לקבל אסימון. כשמאשרים הגדרות של פרטי כניסה ממקור חיצוני, צריך לאמת את ההגדרה לפני שמשתמשים בה. אם לא מאמתים את ההגדרה, גורם זדוני עלול להשתמש בהרשאה כדי לפגוע במערכות ובנתונים שלכם.
אימות הגדרות של פרטי כניסה ממקורות חיצוניים
האופן שבו צריך לאמת את פרטי הכניסה החיצוניים תלוי בסוגי פרטי הכניסה שהאפליקציה מקבלת.
אימות מפתחות של חשבונות שירות
אם האפליקציה מקבלת רק מפתחות של חשבונות שירות, צריך להשתמש בטוען פרטי כניסה שספציפי למפתחות של חשבונות שירות, כמו בדוגמאות הבאות. רכיב טעינת האישורים הספציפי לסוג מנתח רק את השדות שקיימים במפתחות של חשבונות שירות, שלא חושפים נקודות חולשה.
אם אי אפשר להשתמש בטוען פרטי כניסה ספציפי לסוג, צריך לאמת את פרטי הכניסה על ידי אישור שהערך בשדה type הוא service_account. אם הערך בשדה type הוא ערך אחר, אל תשתמשו במפתח של חשבון השירות.
[[["התוכן קל להבנה","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"]],["עדכון אחרון: 2026-03-05 (שעון UTC)."],[],[]]