אימות באמצעות מפתחות API

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

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

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

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

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

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

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

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

כדי לנהל מפתחות API, עליכם להיות בתפקיד אדמין של מפתחות API (roles/serviceusage.apiKeysAdmin) בפרויקט.

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

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

מסוף

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

gcloud

אפשר להשתמש בדוגמאות של CLI של gcloud שבדף הזה בכל אחת מסביבות הפיתוח הבאות:

  • Cloud Shell: כדי להשתמש בטרמינל אונליין שבו כבר מוגדר ה-CLI של gcloud, צריך להפעיל את Cloud Shell.

    בחלק התחתון של הדף הזה מתחיל סשן של Cloud Shell ומופיעה הנחיה של שורת הפקודה. הסשן יופעל תוך כמה שניות.

  • מעטפת מקומית: כדי להשתמש ב-CLI של gcloud בסביבת פיתוח מקומית, מתקינים ומאתחלים את ה-CLI של gcloud.

Java

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

  1. מתקינים ומפעילים את ה-CLI של Google Cloud.
  2. מגדירים את Application Default Credentials בסביבה המקומית באמצעות פרטי הכניסה של המשתמש:

    gcloud auth application-default login

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

Python

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

  1. מתקינים ומפעילים את ה-CLI של Google Cloud.
  2. מגדירים את Application Default Credentials בסביבה המקומית באמצעות פרטי הכניסה של המשתמש:

    gcloud auth application-default login

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

REST

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

  1. מתקינים ומפעילים את ה-CLI של Google Cloud.

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

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

מסוף

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

    לדף Credentials

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

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

gcloud

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

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

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

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: השם או המזהה של הפרויקט ב-Google Cloud.
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.googleapis.com/v2/projects/PROJECT/locations/global/keys"

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

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

שימוש במפתח API

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

שימוש במפתח API באמצעות REST

תוכלו להעביר את מפתח ה-API למצב קריאה ל-API ל-REST כפרמטר של שאילתה, לפי הפורמט הבא, תוך החלפת הערך API_KEY במחרוזת המפתח של מפתח ה-API.

לדוגמה, כדי להעביר מפתח API לבקשת Cloud Natural Language API עבור documents.analyzeEntities:

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY

לחלופין, אפשר להשתמש בכותרת x-goog-api-key כדי להעביר את המפתח. חייבים להשתמש בכותרת הזו יחד עם בקשות ל-gRPC.

curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "X-goog-api-key: API_KEY" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://translation.googleapis.com/language/translate/v2"

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

התמיכה במפתחות API בספריית לקוח היא ספציפית לשפה.

Python

כדי להדגים איך מספקים מפתח API לספרייה, בדוגמה הזו נשתמש ב-Cloud Natural Language API שתומך במפתחות API לאימות.

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


from google.cloud import language_v1

def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
    """
    Authenticates with an API key for Google Language service.

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

    Args:
        quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
        api_key_string: The API key to authenticate to the service.
    """

    # Initialize the Language Service client and set the API key and the quota project id.
    client = language_v1.LanguageServiceClient(
        client_options={"api_key": api_key_string, "quota_project_id": quota_project_id}
    )

    text = "Hello, world!"
    document = language_v1.Document(
        content=text, type_=language_v1.Document.Type.PLAIN_TEXT
    )

    # Make a request to analyze the sentiment of the text.
    sentiment = client.analyze_sentiment(
        request={"document": document}
    ).document_sentiment

    print(f"Text: {text}")
    print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
    print("Successfully authenticated using the API key")

אבטחה של מפתח API

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

  • להוסיף למפתח הגבלות על מפתחות API.

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

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

  • מדי פעם ליצור מחדש את מפתחות ה-API.

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

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

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

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

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

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

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

גורמים מפנים מסוג HTTP

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

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

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

אפשר להוסיף למפתח API עד 1,200 גורמים מפנים מסוג HTTP.

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

תרחיש הגבלות
הרשאה של כתובת 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 במסוף Google Cloud:

    לדף Credentials

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

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

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

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

gcloud

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

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

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

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

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

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

    gcloud beta 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 בשם או במזהה של הפרויקט ב-Google Cloud.

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

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

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

    • ALLOWED_REFERRER_1: ההגבלה על הגורמים המפנים מסוג HTTP.

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

    • PROJECT_ID: השם או המזהה של הפרויקט ב-Google Cloud.

    • 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.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

למידע נוסף על הוספת הגבלות על גורמים מפנים מסוג HTTP למפתח באמצעות 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)

השימוש ב-localhost לא נתמך כאשר קיימות הגבלות על שרתים.

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

מסוף

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

    לדף Credentials

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

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

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

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

gcloud

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

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

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

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

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

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

    gcloud beta 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 בשם או במזהה של הפרויקט ב-Google Cloud.

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

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

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

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

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

    • PROJECT_ID: השם או המזהה של הפרויקט ב-Google Cloud.

    • 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.googleapis.com/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_name
  • x-android_cert_fingerprint

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

מסוף

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

    לדף Credentials

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

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

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

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

gcloud

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

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

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

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

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

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

    gcloud beta 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 בשם או במזהה של הפרויקט ב-Google Cloud.

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

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

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

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

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

    • PROJECT_ID: השם או המזהה של הפרויקט ב-Google Cloud.

    • 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.googleapis.com/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 במסוף Google Cloud:

    לדף Credentials

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

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

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

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

gcloud

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

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

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

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

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

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

    gcloud beta 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 בשם או במזהה של הפרויקט ב-Google Cloud.

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

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

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

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

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

    • PROJECT_ID: השם או המזהה של הפרויקט ב-Google Cloud.

    • 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.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

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

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

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

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

מסוף

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

    לדף Credentials

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

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

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

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

gcloud

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

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

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

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

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

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

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

    gcloud beta 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 בשם או במזהה של הפרויקט ב-Google Cloud.

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

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

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

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

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

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

    • PROJECT_ID: השם או המזהה של הפרויקט ב-Google Cloud.

    • 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.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

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

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

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

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

gcloud

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

 gcloud beta 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.googleapis.com/v2/keys:lookupKey?keyString=KEY_STRING"

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

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

מסוף

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

    לדף Credentials

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

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

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

gcloud

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

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

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

    gcloud beta services api-keys undelete KEY_ID
    

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

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

REST

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

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

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

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/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.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID:undelete"
    

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

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

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

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

ב-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.googleapis.com/v2/OPERATION_NAME"

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

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

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

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