ניהול מפתחות API

בדף הזה מוסבר איך ליצור, לערוך ולהגביל מפתחות API. במאמר שימוש במפתחות API לגישה לממשקי API מוסבר איך משתמשים במפתחות API כדי לגשת לממשקי API של Google.

מבוא למפתחות API

יש שני סוגים של מפתחות API: מפתחות API רגילים ומפתחות הרשאה. שני המפתחות מאפשרים לכם לשייך בקשה לפרויקט למטרות חיוב וניהול מכסות. עם זאת, יש ביניהם הבדל:

  • מפתח API רגיל לא מאמת חשבון משתמש.

  • מפתח הרשאה מאמת כחשבון שירות. הוא פועל באופן דומה לאסימון גישה לטווח ארוך.

הדף Credentials במסוףCloud de Confiance מוודא שנוצר סוג נכון של מפתח API עבור API שנבחר.

מפתחות API רגילים

מפתחות API רגילים מאפשרים לשייך בקשה לפרויקט לצורכי חיוב ומכסה. כשמשתמשים במפתח API רגיל (מפתח API שלא קושר לחשבון שירות) כדי לגשת ל-API, מפתח ה-API לא מזהה חשבון משתמש. בלי חשבון משתמש, הבקשה לא יכולה להשתמש בניהול זהויות והרשאות גישה (IAM) כדי לבדוק אם למבצע הקריאה יש הרשאה לבצע את הפעולה המבוקשת.

אפשר להשתמש במפתחות API רגילים עם כל API שמקבל מפתחות API, אלא אם נוספו למפתח הגבלות על API. אי אפשר להשתמש במפתחות API רגילים בשירותים שלא תומכים במפתחות API, כולל במצב אקספרס.

מפתחות הרשאה

מפתחות הרשאה הם מפתחות API שמקושרים לחשבון שירות. כשמשתמשים במפתח הרשאה כדי לגשת ל-API, הבקשה מעובדת כאילו השתמשתם בחשבון השירות המקושר כדי לשלוח את הבקשה.

ממשקי API שתומכים במפתחות הרשאה כוללים את Vertex AI (aiplatform.googleapis.com) ואת Gemini API (generativelanguage.googleapis.com).

כשמשתמשים במפתחות הרשאה, חשוב לזכור את הנקודות הבאות:

רכיבים של מפתח API

מפתח API כולל את הרכיבים הבאים, שתוכלו להשתמש בהם כדי לנהל את המפתח ולהשתמש בו:

String
המחרוזת של מפתח API היא מחרוזת מוצפנת, כמו AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe. כשמשתמשים במפתח API כדי לגשת לממשק API, משתמשים תמיד במחרוזת של המפתח. למפתחות API לא משויך קובץ JSON.
מזהה
בכלי הניהול נעשה שימוש במזהה של מפתח API כדי לזהות את המפתח באופן ייחודי. Cloud de Confiance אי אפשר להשתמש במזהה המפתח כדי לגשת לממשקי API. תוכלו לאתר את מזהה המפתח בכתובת ה-URL של דף העריכה של המפתח במסוף Cloud de Confiance . אפשר לאתר את מזהה המפתח גם כשרושמים את המפתחות שבפרויקט באמצעות Google Cloud CLI.
השם המוצג
השם המוצג הוא שם תיאורי אופציונלי למפתח, ואפשר להגדיר אותו כשיוצרים את המפתח וכשמעדכנים אותו.
חשבון שירות שמוגדר כברירת מחדל
מפתחות הרשאה כוללים את כתובת האימייל של חשבון השירות.

לפני שמתחילים

כדי להשתמש בדוגמאות בדף הזה, צריך לבצע את המשימות הבאות.

מגדירים אימות

צריך לבחור את הכרטיסייה הרלוונטית לאופן שבו תכננתם להשתמש בדוגמאות בדף הזה:

המסוף

כשמשתמשים במסוף Cloud de Confiance כדי לגשת לשירותים ולממשקי ה-API, לא צריך להגדיר אימות. Cloud de Confiance by S3NS

gcloud

התקינו את ה-CLI של Google Cloud ואז היכנסו ל-CLI של gcloud באמצעות הזהות המאוחדת שלכם. אחרי שנכנסתם לחשבון, אתחלו את ה-CLI של Google Cloud באמצעות הפקודה הבאה:

gcloud init

C++‎

כדי להשתמש בדוגמאות של C++‎ שבדף הזה בסביבת פיתוח מקומית, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

  1. התקינו את ה-CLI של Google Cloud.

  2. הגדירו שה-CLI של gcloud ישתמש בזהות המאוחדת שלכם.

    איך נכנסים ל-CLI של gcloud באמצעות הזהות המאוחדת?

  3. יוצרים פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

למידע נוסף, ראו הגדרת ADC לסביבת פיתוח מקומית במאמרי העזרה בנושא אימות Cloud de Confiance .

Java

כדי להשתמש בדוגמאות של Java שבדף הזה בסביבת פיתוח מקומית, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

  1. התקינו את ה-CLI של Google Cloud.

  2. הגדירו שה-CLI של gcloud ישתמש בזהות המאוחדת שלכם.

    איך נכנסים ל-CLI של gcloud באמצעות הזהות המאוחדת?

  3. יוצרים פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

למידע נוסף, ראו הגדרת ADC לסביבת פיתוח מקומית במאמרי העזרה בנושא אימות Cloud de Confiance .

Python

כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של Python שבדף הזה, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

  1. התקינו את ה-CLI של Google Cloud.

  2. הגדירו שה-CLI של gcloud ישתמש בזהות המאוחדת שלכם.

    איך נכנסים ל-CLI של gcloud באמצעות הזהות המאוחדת?

  3. יוצרים פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

למידע נוסף, ראו הגדרת ADC לסביבת פיתוח מקומית במאמרי העזרה בנושא אימות Cloud de Confiance .

REST

כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של API בארכיטקטורת REST שבדף הזה, צריך להשתמש בפרטי הכניסה שאתם נותנים ל-CLI של gcloud.

    התקינו את ה-CLI של Google Cloud ואז היכנסו ל-CLI של gcloud באמצעות הזהות המאוחדת שלכם.

מידע נוסף מופיע במאמר אימות לשימוש ב-REST במסמכי האימות של Cloud de Confiance .

התפקידים הנדרשים

כדי לקבל את ההרשאות שדרושות לניהול מפתחות API, צריך לבקש מהאדמין להקצות לכם את תפקידי ה-IAM הבאים בפרויקט:

להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.

הפעלת מפתחות הרשאה

כדי ליצור מפתח הרשאה, צריך קודם להגדיר את אילוץ המדיניות הארגונית constraints/iam.managed.disableServiceAccountApiKeyCreation לערך false. כדי לשנות את מדיניות הארגון צריך משאב ארגוני משויך. אין תמיכה בפרויקטים שלא משויכים לארגון.

כדי לשנות את הגבלת המדיניות, פועלים לפי ההוראות הבאות.

המסוף

  1. במסוף Cloud de Confiance , נכנסים לדף מדיניות הארגון.

    מעבר למדיניות הארגון

  2. עוברים לארגון, לתיקייה או לפרויקט שרוצים לשנות את המדיניות שלהם.

  3. בתיבה Filter, מזינים Block service ולוחצים על שם המסנן Block חשבון שירות מפתחות API קישורים.

  4. לוחצים על ניהול המדיניות.

  5. בקטע Policy source, בוחרים באפשרות Override parent's policy.

  6. לוחצים על Add a rule (הוספת כלל) ומגדירים את Enforcement (אכיפה) לOff (מושבת).

  7. לוחצים על סיום.

  8. אופציונלי: לוחצים על בדיקת שינויים כדי לקבל תובנות לגבי האופן שבו המדיניות המוצעת עלולה לגרום להפרות של דרישות התאימות או לשיבושים.

  9. לוחצים על הגדרת מדיניות.

gcloud

  1. יוצרים קובץ בשם spec.yaml עם התוכן הבא:

    name: SCOPE/SCOPE_ID/policies/iam.managed.disableServiceAccountApiKeyCreation
    spec:
      rules:
      - enforce: false
    

    מספקים את הערכים הבאים:

    • SCOPE: organizations,‏ folders או projects.

    • SCOPE_ID: בהתאם ל-SCOPE, המזהה של הארגון, התיקייה או הפרויקט שאליהם חלה מדיניות הארגון.

  2. מריצים את הפקודה gcloud הבאה כדי לאפשר קישור של מפתחות API לחשבונות שירות:

    gcloud org-policies set-policy spec.yaml \
        --update-mask spec
    

יצירה של מפתח API

יש כמה דרכים ליצור מפתח API:

המסוף

  1. נכנסים לדף Credentials במסוף Cloud de Confiance :

    כניסה לדף Credentials

  2. לוחצים על Create credentials ובתפריט בוחרים באפשרות API key.

  3. מוסיפים לפחות הגבלה אחת על מפתח API. מידע נוסף זמין במאמר בנושא החלת הגבלות על מפתחות API.

  4. אופציונלי: כדי לקשר את מפתח ה-API לחשבון שירות וליצור מפתח הרשאה, מסמנים את התיבה Authenticate API calls through a service account ולוחצים על Select a service account כדי לבחור את חשבון השירות שרוצים לקשר למפתח.

    מידע נוסף זמין במאמר בנושא מפתחות הרשאה.

  5. לוחצים על יצירה. בתיבת הדו-שיח API key created מוצגת המחרוזת של המפתח החדש שיצרתם.

gcloud

משתמשים בפקודה gcloud services api-keys create כדי ליצור מפתח API.

 gcloud services api-keys create \
     --display-name=DISPLAY_NAME \
     --api-target=service=SERVICE_1 \
     --api-target=service=SERVICE_2

מחליפים את הערכים הבאים:

  • DISPLAY_NAME: שם תיאורי למפתח.

  • SERVICE_1,‏ SERVICE_2: שמות השירותים של ממשקי ה-API שאפשר לגשת אליהם באמצעות המפתח.

    תוכלו למצוא את שם השירות על ידי חיפוש ה-API במרכז הבקרה של ה-API. השמות של שירותים הם מחרוזות כמו bigquery.googleapis.com.

    כדי לקשר את מפתח ה-API לחשבון שירות וליצור מפתח הרשאה לשירותים כמו Vertex AI ו-Gemini API, משתמשים ב-gcloud beta במקום זאת, עם הדגל --service-account:

    gcloud beta services api-keys create \
        --display-name=DISPLAY_NAME \
        --api-target=service=SERVICE_1 \
        --api-target=service=SERVICE_2 \
        --service-account=SERVICE_ACCOUNT_EMAIL_ADDRESS
    

    מידע נוסף זמין במאמר בנושא מפתחות הרשאה.

C++‎

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח של מפתחות API.

#include "google/cloud/apikeys/v2/api_keys_client.h"
#include "google/cloud/location.h"

google::api::apikeys::v2::Key CreateApiKey(
    google::cloud::apikeys_v2::ApiKeysClient client,
    google::cloud::Location location, std::string display_name) {
  google::api::apikeys::v2::CreateKeyRequest request;
  request.set_parent(location.FullName());
  request.mutable_key()->set_display_name(std::move(display_name));
  // As an example, restrict the API key's scope to the Natural Language API.
  request.mutable_key()->mutable_restrictions()->add_api_targets()->set_service(
      "language.googleapis.com");

  // Create the key, blocking on the result.
  auto key = client.CreateKey(request).get();
  if (!key) throw std::move(key.status());
  std::cout << "Successfully created an API key: " << key->name() << "\n";

  // For authenticating with the API key, use the value in `key->key_string()`.

  // The API key's resource name is the value in `key->name()`. Use this to
  // refer to the specific key in a `GetKey()` or `DeleteKey()` RPC.
  return *key;
}

Java

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח google-cloud-apikeys.


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.ApiTarget;
import com.google.api.apikeys.v2.CreateKeyRequest;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.LocationName;
import com.google.api.apikeys.v2.Restrictions;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateApiKey {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    //  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 create API keys.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    createApiKey(projectId);
  }

  // Creates an API key.
  public static void createApiKey(String projectId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      Key key = Key.newBuilder()
          .setDisplayName("My first API key")
          // Set the API key restriction.
          // You can also set browser/ server/ android/ ios based restrictions.
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys#api_key_restrictions
          .setRestrictions(Restrictions.newBuilder()
              // Restrict the API key usage by specifying the target service and methods.
              // The API key can only be used to authenticate the specified methods in the service.
              .addApiTargets(ApiTarget.newBuilder()
                  .setService("translate.googleapis.com")
                  .addMethods("translate.googleapis.com.TranslateText")
                  .build())
              .build())
          .build();

      // Initialize request and set arguments.
      CreateKeyRequest createKeyRequest = CreateKeyRequest.newBuilder()
          // API keys can only be global.
          .setParent(LocationName.of(projectId, "global").toString())
          .setKey(key)
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.createKeyAsync(createKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      // To restrict the usage of this API key, use the value in "result.getName()".
      System.out.printf("Successfully created an API key: %s", result.getName());
    }
  }
}

Python

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח של מפתחות API.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def create_api_key(project_id: str, suffix: str) -> Key:
    """
    Creates and restrict an API key. Add the suffix for uniqueness.

    TODO(Developer):
    1. Before running this sample,
      set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    2. Make sure you have the necessary permission to create API keys.

    Args:
        project_id: Google Cloud project id.

    Returns:
        response: Returns the created API Key.
    """
    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    key = api_keys_v2.Key()
    key.display_name = f"My first API key - {suffix}"

    # Initialize request and set arguments.
    request = api_keys_v2.CreateKeyRequest()
    request.parent = f"projects/{project_id}/locations/global"
    request.key = key

    # Make the request and wait for the operation to complete.
    response = client.create_key(request=request).result()

    print(f"Successfully created an API key: {response.name}")
    # For authenticating with the API key, use the value in "response.key_string".
    # To restrict the usage of this API key, use the value in "response.name".
    return response

REST

משתמשים ב-method ‏keys.create כדי ליצור מפתח API. בעקבות הבקשה הזו מתקבלת פעולה ממושכת, וצריך לדגום את הפעולה כדי לאתר את המידע על המפתח החדש.

curl -X POST \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
          "displayName" : "DISPLAY_NAME",
          "restrictions" : {
            "apiTargets": [
              {
                "service": "SERVICE_1"
              },
              {
                "service" : "SERVICE_2"
              },
            ]
          }
        }' \
     "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys"

מחליפים את הערכים הבאים:

  • DISPLAY_NAME: שם תיאורי למפתח.

  • PROJECT_ID: מזהה הפרויקט או השם שלך ב- Cloud de Confiance by S3NS .

  • SERVICE_1,‏ SERVICE_2: שמות השירותים של ממשקי ה-API שאפשר לגשת אליהם באמצעות המפתח.

תוכלו למצוא את שם השירות על ידי חיפוש ה-API במרכז הבקרה של ה-API. השמות של שירותים הם מחרוזות כמו bigquery.googleapis.com.

אופציונלי: כדי לקשר את מפתח ה-API לחשבון שירות וליצור במקומו מפתח הרשאה, משתמשים בפקודה הבאה:

curl -X POST \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
          "displayName" : "DISPLAY_NAME",
          "restrictions" : {
            "apiTargets": [
              {
                "service": "SERVICE_1"
              },
              {
                "service" : "SERVICE_2"
              },
            ]
          },
          "serviceAccountEmail" : "SERVICE_ACCOUNT_EMAIL_ADDRESS"
        }' \
     "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys"

מידע נוסף זמין במאמר בנושא מפתחות הרשאה.

מידע נוסף על יצירת מפתחות API באמצעות API בארכיטקטורת REST מופיע במאמר יצירת מפתח API במאמרי העזרה של ה-API של מפתחות API.

החלת הגבלות על מפתחות API

מפתחות API ללא הגבלות לא מאובטחים. כדי לצמצם את סיכוני האבטחה, אפשר להגביל את מפתחות ה-API בדרכים הבאות:

  • הגבלות על ממשקי API: הגבלת מפתח API כך שאפשר להשתמש בו רק עם קבוצה ספציפית של ממשקי API. אפשר להשתמש במפתחות API ללא הגבלות על API עם כל ממשקי ה-API שמקבלים מפתחות שנוצרו על ידי Cloud de Confiance by S3NS.

  • הגבלות על אפליקציות: הגבלת מפתח API כך שניתן יהיה להשתמש בו רק באתרים, בכתובות IP או באפליקציות ספציפיות. אפשר להשתמש במפתחות API ללא הגבלות על אפליקציות מכל מקום.

מומלץ להגדיר גם הגבלות על ממשקי API וגם הגבלות על אפליקציות.

כדי ליצור מפתח API, צריך להוסיף לפחות הגבלה אחת על ה-API במסוף Cloud de Confiance . עם זאת, כשיוצרים מפתחות API באמצעות ה-CLI של gcloud או ה-API בארכיטקטורת REST, המפתחות לא מוגבלים אלא אם מציינים הגבלה. כדי לעשות את זה, מוסיפים את ההגבלות הבאות כשיוצרים מפתח API:

  • ה-CLI של gcloud: הדגל --api-target, יחד עם ההגבלות על ה-API שרוצים להוסיף.

  • REST: האובייקט restrictions בגוף הבקשה, שמכיל מערך apiTargets שמציין את ההגבלות שרוצים להוסיף.

הוספת הגבלות על ממשקי API

ההגבלות על ממשקי API מציינות לאילו ממשקי API אפשר לקרוא באמצעות מפתח ה-API.

אפשר להוסיף הגבלות API באמצעות אחת מהאפשרויות הבאות:

המסוף

  1. נכנסים לדף Credentials במסוף Cloud de Confiance :

    כניסה לדף Credentials

  2. לוחצים על השם של מפתח ה-API שרוצים להגביל.

  3. בקטע API restrictions, לוחצים על Restrict key.

  4. בוחרים את כל ממשקי ה-API שאפשר לגשת אליהם באמצעות מפתח ה-API שלכם.

  5. כדי לשמור את השינויים ולחזור לרשימה של מפתחות ה-API, לוחצים על Save.

gcloud

  1. מאתרים את המזהה של המפתח שרוצים להגביל.

    המזהה הוא לא השם המוצג או מחרוזת המפתח. כדי לאתר אותו, בעזרת הפקודה gcloud services api-keys list תוכלו להציג את רשימת המפתחות בפרויקט.

  2. משתמשים בפקודה gcloud services api-keys update כדי לציין את השירותים שאליהם אפשר לגשת באמצעות מפתח API.

    מחליפים את הערכים הבאים:

    • KEY_ID: המזהה של המפתח שרוצים להגביל.
    • SERVICE_1,‏ SERVICE_2: שמות השירותים של ממשקי ה-API שאפשר לגשת אליהם באמצעות המפתח.

      עליכם לפרט בפקודת העדכון את כל שמות השירותים, והם יחליפו את כל השירותים הקיימים במפתח.

    תוכלו למצוא את שם השירות על ידי חיפוש ה-API במרכז הבקרה של ה-API. השמות של השירותים הם מחרוזות כמו bigquery.googleapis.com.

    gcloud services api-keys update KEY_ID \
    --api-target=service=SERVICE_1 --api-target=service=SERVICE_2

Java

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח google-cloud-apikeys.


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.ApiTarget;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyApi {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyApi(projectId, keyId);
  }

  // Restricts an API key. Restrictions specify which APIs can be called using the API key.
  public static void restrictApiKeyApi(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the target service and methods.
      // The API key can only be used to authenticate the specified methods in the service.
      Restrictions restrictions = Restrictions.newBuilder()
          .addApiTargets(ApiTarget.newBuilder()
              .setService("translate.googleapis.com")
              .addMethods("translate.googleapis.com.TranslateText")
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח של מפתחות API.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def restrict_api_key_api(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key. Restrictions specify which APIs can be called using the API key.

    TODO(Developer): Replace the variables before running the sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage by specifying the target service and methods.
    # The API key can only be used to authenticate the specified methods in the service.
    api_target = api_keys_v2.ApiTarget()
    api_target.service = "translate.googleapis.com"
    api_target.methods = ["transate.googleapis.com.TranslateText"]

    # Set the API restriction(s).
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.api_targets = [api_target]

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. מאתרים את המזהה של המפתח שרוצים להגביל.

    המזהה הוא לא השם המוצג או מחרוזת המפתח. אפשר לאתר אותו באמצעות method‏ keys.list. המזהה מופיע בשדה uid של התשובה.

    מחליפים את PROJECT_ID במזהה הפרויקט או בשם הפרויקט ב- Cloud de Confiance by S3NS .

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys/"
  2. משתמשים ב-method‏ keys.patch כדי לציין את השירותים שאפשר לגשת אליהם באמצעות מפתח API.

    בעקבות הבקשה הזו מתקבלת פעולה ממושכת, וצריך לדגום את הפעולה כדי לדעת מתי היא הושלמה ומה הסטטוס שלה.

    מחליפים את הערכים הבאים:

    • SERVICE_1,‏ SERVICE_2: שמות השירותים של ממשקי ה-API שאפשר לגשת אליהם באמצעות המפתח.

      עליכם לפרט בבקשה את כל שמות השירותים, והם יחליפו את כל השירותים הקיימים במפתח.

      תוכלו למצוא את שם השירות על ידי חיפוש ה-API במרכז הבקרה של ה-API. השמות של השירותים הם מחרוזות כמו bigquery.googleapis.com.

    • PROJECT_ID: השם או מזהה הפרויקט ב- Cloud de Confiance by S3NS .

    • KEY_ID: המזהה של המפתח שרוצים להגביל.

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "apiTargets": [
      {
        "service": "SERVICE_1"
      },
      {
        "service" : "SERVICE_2"
      },
    ]
    }
    }' \
    "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

למידע נוסף על הוספת הגבלות על ממשקי API למפתח באמצעות API ל-REST, ראו הוספת הגבלות על ממשקי API במאמרי העזרה בנושא API של מפתחות API.

הוספת הגבלות על אפליקציות

הגבלות על אפליקציות מציינות אילו כתובות IP, אפליקציות ואתרים יכולים להשתמש במפתח API.

ניתן להחיל רק סוג אחד של הגבלה על אפליקציות בכל פעם. מומלץ לבחור את סוג ההגבלה בהתאם לסוג האפליקציה:

אפשרות סוג האפליקציה הערות
אתרים אפליקציות אינטרנט קובעת באילו אתרים אפשר להשתמש במפתח.
כתובות IP אפליקציות שנקראו על ידי שרתים ספציפיים קובעת באילו שרתים או משימות cron אפשר להשתמש במפתח. זו ההגבלה היחידה שזמינה למפתחות הרשאה.
אפליקציות ל-Android אפליקציות ל-Android קובעת באיזו אפליקציית Android אפשר להשתמש במפתח.
אפליקציות ל-iOS אפליקציות ל-iOS קובעת באילו חבילות ל-iOS אפשר להשתמש במפתח.

Websites

כדי לקבוע באילו אתרים אפשר להשתמש במפתחות ה-API, אפשר להוסיף גורם מפנה אחד או יותר מסוג HTTP כהגבלות גישה לאתרים. לדוגמה, אם מוסיפים את https://example.com להגבלות גישה לאתרים של מפתח API, רק קריאות מ-https://example.com יכולות להשתמש במפתח ה-API הזה.

הגורמים המפנים מסוג HTTP שמשמשים בהגבלות גישה לאתרים תומכים בתווים כלליים באופן מוגבל. אפשר להחליף תת-דומיין או נתיב בתו כללי לחיפוש (*), אבל אי אפשר להוסיף תו כללי לחיפוש באמצע כתובת ה-URL. לדוגמה, ההגבלה *.example.com תקינה, והיא מקבלת את כל האתרים שמסתיימים ב-.example.com. עם זאת, ההגבלה mysubdomain*.example.com לא תקינה.

אפשר לכלול מספרי יציאות בהגבלות גישה לאתרים. אם כוללים מספר יציאה, מתבצעת התאמה רק לבקשות שנשלחות באמצעות אותה היציאה. אם לא מציינים מספר יציאה, מתבצעת התאמה לבקשות שנשלחות מכל מספרי היציאות.

בטבלה הבאה מוצגים תרחישים לדוגמה והגבלות לדפדפנים:

תרחיש הגבלות
הרשאה של כתובת URL ספציפית צריך להוסיף כתובת URL עם נתיב מדויק, לדוגמה:
www.example.com/path
www.example.com/path/path

בדפדפנים מסוימים חלה מדיניות לגורם מפנה ששולחת רק את כתובת ה-URL המקורית של בקשות ממקורות שונים. משתמשים בדפדפנים האלה לא יכולים להשתמש במפתחות עם מגבלות לכתובות URL ספציפיות לדף.

הרשאה של כל כתובת URL באתר שלכם צריך להגדיר שתי כתובות URL ברשימה allowedReferers.
  1. כתובת ה-URL של הדומיין, בלי תת-דומיין ועם תו כללי לחיפוש של הנתיב, לדוגמה:
    example.com/*
  2. כתובת URL שנייה עם תו כללי לחיפוש לתת-הדומיין ותווים כלליים לחיפוש לנתיב, לדוגמה:
    *.example.com/*
הרשאה של כל כתובת URL בתת-דומיין יחיד או בדומיין ללא קידומת

צריך להגדיר שתי כתובות URL ברשימה allowedReferers כדי להעניק הרשאה ברמת הדומיין:

  1. כתובת ה-URL של הדומיין בלי קו נטוי עוקב, לדוגמה:
    www.example.com
    sub.example.com
    example.com
  2. כתובת URL שנייה של הדומיין עם תו כללי לחיפוש עבור הנתיב, לדוגמה:
    www.example.com/*
    sub.example.com/*
    example.com/*

אפשר להגביל את מפתח ה-API לאתרים ספציפיים באמצעות אחת מהאפשרויות הבאות:

המסוף

  1. נכנסים לדף Credentials במסוף Cloud de Confiance :

    כניסה לדף Credentials

  2. לוחצים על השם של מפתח ה-API שרוצים להגביל.

  3. בקטע Application restrictions, בוחרים באפשרות Websites.

  4. לכל הגבלה שרוצים להוסיף, לוחצים על Add, מזינים את ההגבלה ולוחצים על Done.

  5. כדי לשמור את השינויים ולחזור לרשימה של מפתחות ה-API, לוחצים על Save.

gcloud

  1. מאתרים את המזהה של המפתח שרוצים להגביל.

    המזהה הוא לא השם המוצג או מחרוזת המפתח. כדי לאתר אותו, בעזרת הפקודה gcloud services api-keys list תוכלו להציג את רשימת המפתחות בפרויקט.

  2. משתמשים בפקודה gcloud services api-keys update כדי להוסיף למפתח API הגבלות גישה לאתרים.

    מחליפים את הערכים הבאים:

    • KEY_ID: המזהה של המפתח שרוצים להגביל.
    • ALLOWED_REFERRER_1: ההגבלה על האתר.

      אפשר להוסיף כמה הגבלות שרוצים, ולהפריד ביניהן באמצעות פסיקים. אתם צריכים לפרט בפקודת העדכון את כל ההגבלות על גורמים מפנים, והן יחליפו את כל ההגבלות הקיימות במפתח על גורמים מפנים.

    gcloud services api-keys update KEY_ID \
     --allowed-referrers="ALLOWED_REFERRER_1"

Java

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח google-cloud-apikeys.


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.BrowserKeyRestrictions;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyHttp {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyHttp(projectId, keyId);
  }

  // Restricts an API key. To restrict the websites that can use your API key,
  // you add one or more HTTP referrer restrictions.
  public static void restrictApiKeyHttp(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage to specific websites by adding them
      // to the list of allowed_referrers.
      Restrictions restrictions = Restrictions.newBuilder()
          .setBrowserKeyRestrictions(BrowserKeyRestrictions.newBuilder()
              .addAllowedReferrers("www.example.com/*")
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח של מפתחות API.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def restrict_api_key_http(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key. To restrict the websites that can use your API key,
    you add one or more HTTP referrer restrictions.

    TODO(Developer): Replace the variables before running this sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage to specific websites by adding them to the list of allowed_referrers.
    browser_key_restrictions = api_keys_v2.BrowserKeyRestrictions()
    browser_key_restrictions.allowed_referrers = ["www.example.com/*"]

    # Set the API restriction.
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.browser_key_restrictions = browser_key_restrictions

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. מאתרים את המזהה של המפתח שרוצים להגביל.

    המזהה הוא לא השם המוצג או מחרוזת המפתח. אפשר לאתר אותו באמצעות method‏ keys.list. המזהה מופיע בשדה uid של התשובה.

    מחליפים את PROJECT_ID במזהה הפרויקט או בשם הפרויקט ב- Cloud de Confiance by S3NS .

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys/"
  2. משתמשים ב-method‏ keys.patch כדי להוסיף למפתח ה-API הגבלות גישה לאתרים.

    בעקבות הבקשה מתקבלת פעולה ממושכת, וצריך לדגום את הפעולה כדי לדעת מתי היא הושלמה ומה הסטטוס שלה.

    מחליפים את הערכים הבאים:

    • ALLOWED_REFERRER_1: ההגבלה על האתר.

      אפשר להוסיף כמה הגבלות שרוצים, ולהפריד ביניהן באמצעות פסיקים. עליכם לפרט בבקשה את כל ההגבלות על הגורמים המפנים, והן יחליפו את כל ההגבלות הקיימות על גורמים מפנים במפתח.

    • PROJECT_ID: השם או מזהה הפרויקט ב- Cloud de Confiance by S3NS .

    • KEY_ID: המזהה של המפתח שרוצים להגביל.

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "browserKeyRestrictions": {
      "allowedReferrers": ["ALLOWED_REFERRER_1"]
    }
    }
    }' \
    "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

למידע נוסף על הוספת הגבלות גישה לאתרים למפתח באמצעות API בארכיטקטורת REST, ראו הוספת הגבלות על דפדפנים במאמרי העזרה של ה-API של מפתחות API.

כתובות IP

אתם יכולים לציין את כתובות ה-IP החיצוניות של מבצעי הקריאות (כמו שרתי אינטרנט או משימות cron) שמורשים להשתמש במפתחות ה-API שלכם. אפשר לציין כתובות IP בפורמטים הבאים:

  • IPv4‏ (198.51.100.1)

  • IPv6‏ (2001:db8::1)

  • תת-רשת עם סימון CIDR (198.51.100.0/24,‏ 2001:db8::/64)

אין תמיכה בכתובות IP פנימיות וב-localhost.

כדי להגביל את מפתח ה-API לכתובות IP חיצוניות ספציפיות, אפשר להשתמש באחת מהאפשרויות הבאות:

המסוף

  1. נכנסים לדף Credentials במסוף Cloud de Confiance :

    כניסה לדף Credentials

  2. לוחצים על השם של מפתח ה-API שרוצים להגביל.

  3. בקטע Application restrictions, בוחרים באפשרות IP addresses.

  4. לכל כתובת IP שרוצים להוסיף, לוחצים על Add, מזינים את הכתובת ולוחצים על Done.

  5. כדי לשמור את השינויים ולחזור לרשימה של מפתחות ה-API, לוחצים על Save.

gcloud

  1. מאתרים את המזהה של המפתח שרוצים להגביל.

    המזהה הוא לא השם המוצג או מחרוזת המפתח. כדי לאתר אותו, בעזרת הפקודה gcloud services api-keys list תוכלו להציג את רשימת המפתחות בפרויקט.

  2. משתמשים בפקודה gcloud services api-keys update כדי להוסיף למפתח API הגבלות על שרתים (כתובת IP).

    מחליפים את הערכים הבאים:

    • KEY_ID: המזהה של המפתח שרוצים להגביל.
    • ALLOWED_IP_ADDR_1: כתובת ה-IP המורשית.

      אפשר להוסיף כמה כתובות IP שרוצים, ולהפריד ביניהן באמצעות פסיקים.

    gcloud services api-keys update KEY_ID \
    --allowed-ips="ALLOWED_IP_ADDR_1"

Java

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח google-cloud-apikeys.


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.ServerKeyRestrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyServer {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyServer(projectId, keyId);
  }

  // Restricts the API key based on IP addresses. You can specify one or more IP addresses
  // of the callers, for example web servers or cron jobs, that are allowed to use your API key.
  public static void restrictApiKeyServer(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the IP addresses.
      // You can specify the IP addresses in IPv4 or IPv6 or a subnet using CIDR notation.
      Restrictions restrictions = Restrictions.newBuilder()
          .setServerKeyRestrictions(ServerKeyRestrictions.newBuilder()
              .addAllAllowedIps(Arrays.asList("198.51.100.0/24", "2000:db8::/64"))
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח של מפתחות API.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def restrict_api_key_server(project_id: str, key_id: str) -> Key:
    """
    Restricts the API key based on IP addresses. You can specify one or more IP addresses of the callers,
    for example web servers or cron jobs, that are allowed to use your API key.

    TODO(Developer): Replace the variables before running this sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage by specifying the IP addresses.
    # You can specify the IP addresses in IPv4 or IPv6 or a subnet using CIDR notation.
    server_key_restrictions = api_keys_v2.ServerKeyRestrictions()
    server_key_restrictions.allowed_ips = ["198.51.100.0/24", "2000:db8::/64"]

    # Set the API restriction.
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.server_key_restrictions = server_key_restrictions

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. מאתרים את המזהה של המפתח שרוצים להגביל.

    המזהה הוא לא השם המוצג או מחרוזת המפתח. אפשר לאתר אותו באמצעות method‏ keys.list. המזהה מופיע בשדה uid של התשובה.

    מחליפים את PROJECT_ID במזהה הפרויקט או בשם של הפרויקט ב- Cloud de Confiance by S3NS .

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys/"
  2. משתמשים ב-method‏ keys.patch כדי להוסיף למפתח API הגבלות על שרתים (כתובת IP).

    בעקבות הבקשה מתקבלת פעולה ממושכת, וצריך לדגום את הפעולה כדי לדעת מתי היא הושלמה ומה הסטטוס שלה.

    מחליפים את הערכים הבאים:

    • ALLOWED_IP_ADDR_1: כתובת ה-IP המורשית.

      אפשר להוסיף כמה כתובות IP שרוצים, ולהפריד ביניהן באמצעות פסיקים. עליכם לפרט בבקשה את כל כתובות ה-IP, כשההגבלות על גורמים מפנים יחליפו את כל ההגבלות הקיימות כתובות IP במפתח.

    • PROJECT_ID: השם או מזהה הפרויקט ב- Cloud de Confiance by S3NS .

    • KEY_ID: המזהה של המפתח שרוצים להגביל.

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
      "serverKeyRestrictions": {
        "allowedIps": ["ALLOWED_IP_ADDR_1"]
      }
    }
    }' \
    "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

למידע נוסף על הוספת הגבלות על כתובות IP למפתח באמצעות API בארכיטקטורת REST, ראו הוספת הגבלות על שרתים במאמרי העזרה של ה-API בנושא API של מפתחות API.

אפליקציות ל-Android

תוכלו להגביל את השימוש במפתח API לאפליקציות מסוימות ל-Android. צריך להעביר לכל אפליקציה את שם החבילה ואת טביעת האצבע לאישור SHA-1 בגודל 20 בייטים.

אם משתמשים במפתח ה-API בבקשה, צריך לציין את שם החבילה ואת טביעת האצבע לאישור באמצעות כותרות ה-HTTP האלה:

  • X-Android-Package
  • X-Android-Cert

כדי להגביל את מפתח ה-API לאפליקציה אחת או יותר ל-Android, תוכלו להשתמש באחת מהאפשרויות הבאות:

המסוף

  1. נכנסים לדף Credentials במסוף Cloud de Confiance :

    כניסה לדף Credentials

  2. לוחצים על השם של מפתח ה-API שרוצים להגביל.

  3. בקטע Application restrictions, בוחרים באפשרות Android apps.

  4. לכל אפליקציה ל-Android שרוצים להוסיף, לוחצים על Add, מזינים את שם החבילה ואת טביעת האצבע לאישור SHA-1 ולוחצים על Done.

  5. כדי לשמור את השינויים ולחזור לרשימה של מפתחות ה-API, לוחצים על Save.

gcloud

  1. מאתרים את המזהה של המפתח שרוצים להגביל.

    המזהה הוא לא השם המוצג או מחרוזת המפתח. כדי לאתר אותו, בעזרת הפקודה gcloud services api-keys list תוכלו להציג את רשימת המפתחות בפרויקט.

  2. משתמשים בפקודה gcloud services api-keys update כדי לציין את האפליקציות ל-Android שבהן אפשר להשתמש במפתח API.

    מחליפים את הערכים הבאים:

    • KEY_ID: המזהה של המפתח שרוצים להגביל.
    • SHA1_FINGERPRINT ו-PACKAGE_NAME: הפרטים של האפליקציה ל-Android שבה אפשר להשתמש במפתח.

      אפשר להוסיף כמה אפליקציות שרוצים, תוך שימוש בדגלי --allowed-application נוספים.

    gcloud services api-keys update KEY_ID \
    --allowed-application=sha1_fingerprint=SHA1_FINGERPRINT_1,package_name=PACKAGE_NAME_1 \
    --allowed-application=sha1_fingerprint=SHA1_FINGERPRINT_2,package_name=PACKAGE_NAME_2

Java

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח google-cloud-apikeys.


import com.google.api.apikeys.v2.AndroidApplication;
import com.google.api.apikeys.v2.AndroidKeyRestrictions;
import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyAndroid {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyAndroid(projectId, keyId);
  }

  // Restricts an API key based on android applications.
  // Specifies the Android application that can use the key.
  public static void restrictApiKeyAndroid(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the allowed android applications.
      Restrictions restrictions = Restrictions.newBuilder()
          .setAndroidKeyRestrictions(AndroidKeyRestrictions.newBuilder()
              .addAllowedApplications(AndroidApplication.newBuilder()
                  // Specify the android application's package name and SHA1 fingerprint.
                  .setPackageName("com.google.appname")
                  .setSha1Fingerprint("0873D391E987982FBBD30873D391E987982FBBD3")
                  .build())
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח של מפתחות API.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def restrict_api_key_android(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key based on android applications.

    Specifies the Android application that can use the key.

    TODO(Developer): Replace the variables before running this sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Specify the android application's package name and SHA1 fingerprint.
    allowed_application = api_keys_v2.AndroidApplication()
    allowed_application.package_name = "com.google.appname"
    allowed_application.sha1_fingerprint = "0873D391E987982FBBD30873D391E987982FBBD3"

    # Restrict the API key usage by specifying the allowed applications.
    android_key_restriction = api_keys_v2.AndroidKeyRestrictions()
    android_key_restriction.allowed_applications = [allowed_application]

    # Set the restriction(s).
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.android_key_restrictions = android_key_restriction

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. מאתרים את המזהה של המפתח שרוצים להגביל.

    המזהה הוא לא השם המוצג או מחרוזת המפתח. אפשר לאתר אותו באמצעות method‏ keys.list. המזהה מופיע בשדה uid של התשובה.

    מחליפים את PROJECT_ID במזהה הפרויקט או בשם הפרויקט ב- Cloud de Confiance by S3NS .

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys/"
  2. משתמשים ב-method‏ keys.patch כדי לציין את האפליקציות ל-Android שבהן אפשר להשתמש במפתח API.

    בעקבות הבקשה מתקבלת פעולה ממושכת, וצריך לדגום את הפעולה כדי לדעת מתי היא הושלמה ומה הסטטוס שלה.

    מחליפים את הערכים הבאים:

    • SHA1_FINGERPRINT_1 ו-PACKAGE_NAME_1: הפרטים של האפליקציה ל-Android שבה אפשר להשתמש במפתח.

      אפשר להוסיף את המידע לכמה אפליקציות שרוצים, ולהפריד בין האובייקטים AndroidApplication באמצעות פסיקים. עליכם לפרט בבקשה את כל האפליקציות, והן יחליפו את כל האפליקציות המורשות הקיימות במפתח.

    • PROJECT_ID: השם או מזהה הפרויקט ב- Cloud de Confiance by S3NS .

    • KEY_ID: המזהה של המפתח שרוצים להגביל.

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "androidKeyRestrictions": {
      "allowedApplications": [
        {
          "sha1Fingerprint": "SHA1_FINGERPRINT_1",
          "packageName": "PACKAGE_NAME_1"
        },
     ]
    }
    }
    }' \
    "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

למידע נוסף על הוספת הגבלות על אפליקציות ל-Android למפתח באמצעות API בארכיטקטורת REST, ראו הוספת הגבלות על Android במאמרי העזרה של ה-API בנושא API של מפתחות API.

אפליקציות ל-iOS

תוכלו להגביל את השימוש במפתח API לאפליקציות ספציפיות ל-iOS באמצעות מזהה החבילה של כל אפליקציה.

אם משתמשים במפתח ה-API בבקשה, צריך לציין את מזהה החבילה באמצעות כותרת ה-HTTP ‏X-Ios-Bundle-Identifier.

כדי להגביל את מפתח ה-API לאפליקציה אחת או יותר ל-iOS, תוכלו להשתמש באחת מהאפשרויות הבאות:

המסוף

  1. נכנסים לדף Credentials במסוף Cloud de Confiance :

    כניסה לדף Credentials

  2. לוחצים על השם של מפתח ה-API שרוצים להגביל.

  3. בקטע Application restrictions, בוחרים באפשרות iOS apps.

  4. לכל אפליקציה ל-iOS שרוצים להוסיף, לוחצים על Add, מזינים את מזהה החבילה ולוחצים על Done.

  5. כדי לשמור את השינויים ולחזור לרשימה של מפתחות ה-API, לוחצים על Save.

gcloud

  1. מאתרים את המזהה של המפתח שרוצים להגביל.

    המזהה הוא לא השם המוצג או מחרוזת המפתח. כדי לאתר אותו, בעזרת הפקודה gcloud services api-keys list תוכלו להציג את רשימת המפתחות בפרויקט.

  2. משתמשים ב-method‏ gcloud services api-keys update כדי לציין את האפליקציות ל-iOS שבהן אפשר להשתמש במפתח.

    מחליפים את הערכים הבאים:

    • KEY_ID: המזהה של המפתח שרוצים להגביל.
    • ALLOWED_BUNDLE_ID: מזהה החבילה של אפליקציה ל-iOS שבה רוצים להשתמש במפתח ה-API הזה.

      אפשר להוסיף כמה מזהי חבילות שרוצים, ולהפריד ביניהם באמצעות פסיקים.

    gcloud services api-keys update KEY_ID \
    --allowed-bundle-ids=ALLOWED_BUNDLE_ID_1,ALLOWED_BUNDLE_ID_2

Java

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח google-cloud-apikeys.


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.IosKeyRestrictions;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyIos {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyIos(projectId, keyId);
  }

  // Restricts an API key. You can restrict usage of an API key to specific iOS apps
  // by providing the bundle ID of each app.
  public static void restrictApiKeyIos(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the bundle ID(s)
      // of iOS app(s) that can use the key.
      Restrictions restrictions = Restrictions.newBuilder()
          .setIosKeyRestrictions(IosKeyRestrictions.newBuilder()
              .addAllAllowedBundleIds(Arrays.asList("com.google.gmail", "com.google.drive"))
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח של מפתחות API.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def restrict_api_key_ios(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key. You can restrict usage of an API key to specific iOS apps
    by providing the bundle ID of each app.

    TODO(Developer): Replace the variables before running this sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage by specifying the bundle ID(s) of iOS app(s) that can use the key.
    ios_key_restrictions = api_keys_v2.IosKeyRestrictions()
    ios_key_restrictions.allowed_bundle_ids = ["com.google.gmail", "com.google.drive"]

    # Set the API restriction.
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.ios_key_restrictions = ios_key_restrictions

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. מאתרים את המזהה של המפתח שרוצים להגביל.

    המזהה הוא לא השם המוצג או מחרוזת המפתח. אפשר לאתר אותו באמצעות method‏ keys.list. המזהה מופיע בשדה uid של התשובה.

    מחליפים את PROJECT_ID במזהה הפרויקט או בשם הפרויקט ב- Cloud de Confiance by S3NS .

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys/"
  2. משתמשים ב-method‏ keys.patch כדי לציין את האפליקציות ל-iOS שבהן אפשר להשתמש במפתח API.

    בעקבות הבקשה מתקבלת פעולה ממושכת, וצריך לדגום את הפעולה כדי לדעת מתי היא הושלמה ומה הסטטוס שלה.

    מחליפים את הערכים הבאים:

    • ALLOWED_BUNDLE_ID: מזהה החבילה של אפליקציה ל-iOS שבה אפשר להשתמש במפתח.

      אפשר להוסיף את המידע לכמה אפליקציות שרוצים, ולהפריד בין מזהי החבילות באמצעות פסיקים. עליכם לפרט בבקשה את כל מזהי החבילות, והם יחליפו את כל האפליקציות המורשות הקיימות במפתח.

    • PROJECT_ID: השם או מזהה הפרויקט ב- Cloud de Confiance by S3NS .

    • KEY_ID: המזהה של המפתח שרוצים להגביל.

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "iosKeyRestrictions": {
      "allowedBundleIds": ["ALLOWED_BUNDLE_ID_1","ALLOWED_BUNDLE_ID_2"]
    }
    }
    }' \
    "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

למידע נוסף על הוספת הגבלות על אפליקציות ל-iOS למפתח באמצעות API ל-REST, ראו הוספת הגבלות על iOS במאמרי העזרה בנושא API של מפתחות API.

הצגת רשימה של מפתחות API ללא הגבלות

אתם יכולים להשתמש במאגר משאבי ענן כדי לרשום את מפתחות ה-API בארגון, בתיקייה או בפרויקט שאין להם הגבלות. כדי לעשות זאת, פועלים לפי השלבים הבאים:

  1. מפעילים את Cloud Asset Inventory API בפרויקט שממנו מריצים פקודות של מאגר משאבי ענן.

    הפעלת Cloud Asset Inventory API

  2. מוודאים שלחשבון שלכם יש תפקיד מתאים להפעלת Cloud Asset Inventory API. למידע על הרשאות ספציפיות לכל סוג שיחה, אפשר לעיין במאמר בנושא הרשאות.

  3. כדי להציג רשימה של מפתחות API ללא הגבלות, מריצים את הפקודה הבאה:

    gcloud asset list \
      --SCOPE \
      --asset-types=apikeys.googleapis.com/Key \
      --content-type=resource \
      --filter="FILTER"
    

    מחליפים את מה שכתוב בשדות הבאים:

    • SCOPE: ההיקף (פרויקט, תיקייה או ארגון) של רשימת מפתחות ה-API. אפשר להשתמש באחד מהערכים הבאים:

      • project=PROJECT_ID, כאשר PROJECT_ID הוא מזהה הפרויקט.

      • folder=FOLDER_ID, כאשר FOLDER_ID הוא מזהה התיקייה.

      • organization=ORGANIZATION_ID, כאשר ORGANIZATION_ID הוא מזהה הארגון.

    • FILTER: מפתחות ה-API שיוצגו ברשימה, על סמך ההגבלות שחסרות להם:

      • -resource.data.restrictions:*: הצגת מפתחות API שחסרות בהם כל ההגבלות.

      • -resource.data.restrictions.apiTargets:*: הצגת מפתחות API שחסרות להם הגבלות API.

      • -resource.data.restrictions.browserKeyRestrictions:*: הצגת מפתחות API שחסרות להם הגבלות גישה לאתרים.

      • -resource.data.restrictions.serverKeyRestrictions:*: הצגת מפתחות API שחסרות להם הגבלות על כתובות IP.

      • -resource.data.restrictions.androidKeyRestrictions:*: הצגת מפתחות API שחסרות להם הגבלות ל-Android.

      • -resource.data.restrictions.iosKeyRestrictions:*: הצגת מפתחות API שחסרות להם הגבלות ל-iOS.

איתור הפרטים של פרויקט ממחרוזת של מפתח

בעזרת המחרוזת של מפתח API אפשר לדעת לאיזה פרויקט הוא משויך. Cloud de Confiance

מחליפים את הערך KEY_STRING במחרוזת המפתח עם פרטי הפרויקט הנדרשים.

gcloud

משתמשים בפקודה gcloud services api-keys lookup כדי לאתר את מזהה הפרויקט במחרוזת של מפתח.

 gcloud services api-keys lookup KEY_STRING
 

Java

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח google-cloud-apikeys.


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.LookupKeyRequest;
import com.google.api.apikeys.v2.LookupKeyResponse;
import java.io.IOException;

public class LookupApiKey {

  public static void main(String[] args) throws IOException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    //  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 view API keys.
    // API key string to retrieve the API key name.
    String apiKeyString = "API_KEY_STRING";

    lookupApiKey(apiKeyString);
  }

  // Retrieves name (full path) of an API key using the API key string.
  public static void lookupApiKey(String apiKeyString) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Initialize the lookup request and set the API key string.
      LookupKeyRequest lookupKeyRequest = LookupKeyRequest.newBuilder()
          .setKeyString(apiKeyString)
          .build();

      // Make the request and obtain the response.
      LookupKeyResponse response = apiKeysClient.lookupKey(lookupKeyRequest);

      System.out.printf("Successfully retrieved the API key name: %s", response.getName());
    }
  }
}

Python

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח של מפתחות API.


from google.cloud import api_keys_v2


def lookup_api_key(api_key_string: str) -> None:
    """
    Retrieves name (full path) of an API key using the API key string.

    TODO(Developer):
    1. Before running this sample,
      set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    2. Make sure you have the necessary permission to view API keys.

    Args:
        api_key_string: API key string to retrieve the API key name.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Initialize the lookup request and set the API key string.
    lookup_key_request = api_keys_v2.LookupKeyRequest(
        key_string=api_key_string,
        # Optionally, you can also set the etag (version).
        # etag=etag,
    )

    # Make the request and obtain the response.
    lookup_key_response = client.lookup_key(lookup_key_request)

    print(f"Successfully retrieved the API key name: {lookup_key_response.name}")

REST

משתמשים ב-method‏ lookupKey כדי לאתר את מזהה הפרויקט במחרוזת של מפתח.

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
"https://apikeys.s3nsapis.fr/v2/keys:lookupKey?keyString=KEY_STRING"

יצירת עותק של מפתח API

אם אתם צריכים מפתח API חדש עם אותן הגבלות כמו מפתח API קיים, אתם יכולים ליצור עותק של מפתח ה-API הקיים. הפעולה הזו יוצרת מפתח API חדש עם מחרוזת מפתח ומזהה ייחודיים, עם ההגבלות של מפתח ה-API הקיים.

הפעולה 'העתקה' זמינה רק במסוף Cloud de Confiance . כדי להשתמש בשיטות אחרות, צריך לפעול לפי השלבים ליצירת מפתח API, ואז להחיל את אותן הגבלות על מפתח ה-API שנוצר.

  1. נכנסים לדף Credentials במסוף Cloud de Confiance :

    כניסה לדף Credentials

  2. לוחצים על השם של מפתח ה-API שרוצים להעתיק.

    נפתח דף הפרטים של מפתח ה-API.

  3. לוחצים על יצירת עותק.

  4. מזינים שם למפתח ה-API החדש ומאשרים שההגבלות נכונות.

  5. לוחצים על יצירה.

החלפת מפתח API

סיבוב תקופתי של מפתחות ה-API מאפשר להגביל את ההשפעה של מפתחות API שנמצאים בסיכון.

כשמבצעים רוטציה של מפתח API, יוצרים מפתח חדש עם אותן הגבלות כמו המפתח הישן, ומעדכנים את האפליקציות כך שישתמשו במפתח החדש. אחרי שמעדכנים את כל האפליקציות, מוחקים את המפתח הישן.

פעולת הרוטציה זמינה רק במסוף Cloud de Confiance . כדי להשתמש בשיטות אחרות, צריך לפעול לפי השלבים ליצירת מפתח API, ואז להחיל את אותן הגבלות על מפתח ה-API שנוצר. אחרי שמעדכנים את האפליקציות כך שישתמשו במפתח החדש, מוחקים את המפתח הישן.

  1. נכנסים לדף Credentials במסוף Cloud de Confiance :

    כניסה לדף Credentials

  2. לוחצים על השם של מפתח ה-API שרוצים להחליף כדי לפתוח את דף הפרטים שלו.

  3. לוחצים על Rotate key (ביצוע רוטציה למפתח).

  4. מזינים שם למפתח ה-API החדש ומאשרים שההגבלות נכונות.

  5. לוחצים על יצירה.

  6. מעתיקים את מחרוזת המפתח ומעדכנים את האפליקציות כדי להשתמש במחרוזת החדשה.

  7. אחרי שמעדכנים את כל האפליקציות כדי להשתמש במפתח החדש, חוזרים לדף הפרטים של המפתח החדש. בקטע Previous key (מפתח קודם), לוחצים על Delete the previous key (מחיקת המפתח הקודם) כדי למחוק את המפתח הישן.

    אם גיליתם שמחקתם את המפתח הישן מוקדם מדי, אתם יכולים לבטל את המחיקה שלו.

ביטול המחיקה של מפתח API

אם מחקתם בטעות מפתח API, תוכלו לבטל את המחיקה (לשחזר אותו) עד 30 יום ממחיקת המפתח. אחרי 30 יום אי אפשר לבטל את המחיקה של מפתח ה-API.

המסוף

  1. נכנסים לדף Credentials במסוף Cloud de Confiance :

    כניסה לדף Credentials

  2. לוחצים על Restore deleted credentials.

  3. מאתרים את מפתח ה-API שרוצים לבטל את המחיקה שלו ולוחצים על Restore.

    ביטול המחיקה של מפתח API יכול להימשך כמה דקות. אחרי ההפצה, מפתח ה-API שהמחיקה שלו בוטלה מוצג ברשימת מפתחות ה-API.

gcloud

  1. מאתרים את המזהה של המפתח שרוצים לבטל את המחיקה שלו.

    המזהה הוא לא השם המוצג או מחרוזת המפתח. כדי לאתר אותו, בעזרת הפקודה gcloud services api-keys list --show-deleted תוכלו להציג את רשימת המפתחות שנמחקו בפרויקט.

  2. משתמשים בפקודה gcloud services api-keys undelete כדי לבטל את המחיקה של מפתח ה-API.

    gcloud services api-keys undelete KEY_ID

    מחליפים את הערכים הבאים:

    • KEY_ID: המזהה של המפתח שרוצים לבטל את המחיקה שלו.

Java

כדי להריץ את הדוגמה הזו, צריך להתקין את ספריית הלקוח google-cloud-apikeys.

import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.UndeleteKeyRequest;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UndeleteApiKey {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project.
    String projectId = "YOUR_PROJECT_ID";
    // The API key id to undelete.
    String keyId = "YOUR_KEY_ID";

    undeleteApiKey(projectId, keyId);
  }

  // Undeletes an API key.
  public static void undeleteApiKey(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Initialize the undelete request and set the argument.
      UndeleteKeyRequest undeleteKeyRequest = UndeleteKeyRequest.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          .build();

      // Make the request and wait for the operation to complete.
      Key undeletedKey = apiKeysClient.undeleteKeyAsync(undeleteKeyRequest)
          .get(3, TimeUnit.MINUTES);

      System.out.printf("Successfully undeleted the API key: %s", undeletedKey.getName());
    }
  }
}

REST

  1. מאתרים את המזהה של המפתח שרוצים לבטל את המחיקה שלו.

    המזהה הוא לא השם המוצג או מחרוזת המפתח. אפשר לאתר אותו באמצעות ה-method ‏keys.list, כשפרמטר השאילתה showDeleted מוגדר ל-true. מזהה המפתח מופיע בשדה uid של התשובה.

    מחליפים את PROJECT_ID במזהה הפרויקט או בשם הפרויקט ב- Cloud de Confiance by S3NS .

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys?showDeleted=true"
  2. משתמשים ב-method‏ undelete כדי לבטל את המחיקה של מפתח ה-API.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://apikeys.s3nsapis.fr/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID:undelete"

    בעקבות הבקשה מתקבלת פעולה ממושכת, וצריך לדגום את הפעולה כדי לדעת מתי היא הושלמה ומה הסטטוס שלה.

    מחליפים את הערכים הבאים:

    • PROJECT_ID: השם או מזהה הפרויקט ב- Cloud de Confiance by S3NS .
    • KEY_ID: המזהה של המפתח שרוצים להגביל.

קביעת סוג מפתח ה-API

כדי לדעת אם מפתח ה-API הוא מפתח רגיל או מפתח הרשאה, צריך לבדוק את המפתח.

המסוף

  1. נכנסים לדף Credentials במסוף Cloud de Confiance :

    כניסה לדף Credentials

    אם מוצג מזהה של חשבון שירות, מפתח ה-API הוא מפתח הרשאה. אם לא מוצג מזהה של חשבון שירות, מפתח ה-API הוא מפתח API רגיל.

gcloud

  1. מאתרים את מזהה המפתח.

    המזהה הוא לא השם המוצג או מחרוזת המפתח. כדי לאתר אותו, בעזרת הפקודה gcloud services api-keys list תוכלו להציג את רשימת המפתחות בפרויקט.

  2. משתמשים בפקודה gcloud services api-keys describe כדי להוסיף תיאור למפתח ה-API.

    gcloud services api-keys describe KEY_ID

    אם מוצג מזהה של חשבון שירות, מפתח ה-API הוא מפתח הרשאה. אם לא מוצג מזהה של חשבון שירות, מפתח ה-API הוא מפתח API רגיל.

דגימה של פעולות ממושכות

ב-methods של API של מפתחות API נעשה שימוש בפעולות ממושכות. אם משתמשים ב-API בארכיטקטורת REST כדי ליצור ולנהל מפתחות API, מבַקשת ה-method הראשונית מתקבל אובייקט פעולה. עליכם להשתמש בשם הפעולה כדי לבצע דגימה של הפעולה הממושכת. כשהתהליך הממושך של הבקשה יסתיים, תוכלו לדגום את הפעולה כדי להציג נתונים מהבקשה.

כדי לדגום פעולה ממושכת של API של מפתחות API, עליכם להשתמש ב-method‏ operations.get.

מחליפים את OPERATION_NAME בשם הפעולה שהתקבל מהפעולה הממושכת. למשל, operations/akmf.p7-358517206116-cd10a88a-7740-4403-a8fd-979f3bd7fe1c.

curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://apikeys.s3nsapis.fr/v2/OPERATION_NAME"

מגבלות על מפתחות API

בכל פרויקט ניתן ליצור עד 300 מפתחות API. זוהי מגבלת מערכת ולא ניתן לבקש הגדלה של המכסה. אם דרושים לכם מפתחות API נוספים, עליכם להשתמש במספר פרויקטים.

אפשר להוסיף למפתח API עד 1,200 הגבלות על אפליקציות.

המאמרים הבאים