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

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

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

יש שני סוגים של מפתחות API: מפתחות API רגילים ומפתחות API שמקושרים לחשבון שירות.

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

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

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

מפתחות API שמקושרים לחשבון שירות

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

ממשק ה-API היחיד שתומך במפתחות API עם הגבלות הוא aiplatform.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.
השם המוצג
השם המוצג הוא שם תיאורי אופציונלי למפתח, ואפשר להגדיר אותו כשיוצרים את המפתח וכשמעדכנים אותו.
חשבון שירות שמוגדר כברירת מחדל
מפתחות API שמשויכים לחשבון שירות כוללים את כתובת האימייל של חשבון השירות.

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

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

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

Select the tab for how you plan to use the samples on this page:

Console

When you use the Cloud de Confiance console to access Cloud de Confiance by S3NS services and APIs, you don't need to set up authentication.

gcloud

Install the Google Cloud CLI, and then sign in to the gcloud CLI with your federated identity. After signing in, initialize the Google Cloud CLI by running the following command:

gcloud init

C++‎

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

  1. Install the Google Cloud CLI.

  2. Configure the gcloud CLI to use your federated identity.

    For more information, see Sign in to the gcloud CLI with your federated identity.

  3. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

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

Java

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

  1. Install the Google Cloud CLI.

  2. Configure the gcloud CLI to use your federated identity.

    For more information, see Sign in to the gcloud CLI with your federated identity.

  3. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

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

Python

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

  1. Install the Google Cloud CLI.

  2. Configure the gcloud CLI to use your federated identity.

    For more information, see Sign in to the gcloud CLI with your federated identity.

  3. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

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

REST

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

    Install the Google Cloud CLI, and then sign in to the gcloud CLI with your federated identity.

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

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

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

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

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

הפעלת קישור מפתחות לחשבונות שירות

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

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

המסוף

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

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

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

  3. בתיבה Filter, מזינים Block service ולוחצים על שם המסנן Block service account API key bindings.

  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 לחשבון שירות, מסמנים את התיבה Authenticate API calls through a service account ולוחצים על Select a service account כדי לבחור את חשבון השירות שרוצים לקשר למפתח.

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

  4. מוסיפים הגבלות על מפתחות API.

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

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

gcloud

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

מחליפים את DISPLAY_NAME בשם שמתאר את המפתח.

 gcloud services api-keys create \
     --display-name=DISPLAY_NAME

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

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

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

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. בעקבות הבקשה הזו מתקבלת פעולה ממושכת, וצריך לדגום את הפעולה כדי לאתר את המידע על המפתח החדש.

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

  • DISPLAY_NAME: אופציונלי. שם תיאורי למפתח.
  • PROJECT_ID: מזהה הפרויקט או השם שלכם ב- Cloud de Confiance by S3NS .
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d {'"displayName" : "DISPLAY_NAME"'} \
"https://apikeys.s3nsapis.fr/v2/projects/PROJECT/locations/global/keys"

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

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

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

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

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

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

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

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

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

אפשרות סוג האפליקציה הערות
אתרים אפליקציות אינטרנט קובעת באילו אתרים אפשר להשתמש במפתח.
כתובות IP אפליקציות שנקראו על ידי שרתים ספציפיים קובעת באילו שרתים או משימות cron אפשר להשתמש במפתח. זו ההגבלה היחידה שזמינה אם מקשרים את מפתח ה-API לחשבון שירות.
אפליקציות ל-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.

אפליקציות ל-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.

אפליקציות ל-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 שרוצים להוסיף, לוחצים על הוספה, מזינים את מזהה החבילה ולוחצים על סיום.

  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 מציינות לאילו ממשקי 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.

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

בעזרת המחרוזת של מפתח 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. לוחצים על ביצוע רוטציה למפתח.

  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 משויך לחשבון שירות, מזהה חשבון השירות מוצג.

gcloud

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

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

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

    gcloud services api-keys describe KEY_ID

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

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

ב-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 הגבלות על אפליקציות.

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