Esegui l'autenticazione mediante chiavi API

Questa pagina descrive come utilizzare le chiavi API per eseguire l'autenticazione nelle API e nei servizi Google Cloud che supportano le chiavi API.

La maggior parte delle API Google Cloud non supporta le chiavi API. Verifica che l'API che vuoi utilizzare supporti le chiavi API prima di utilizzare questo metodo di autenticazione.

Per informazioni sull'utilizzo delle chiavi API per l'autenticazione su Google Maps Platform, consulta la documentazione di Google Maps Platform. Per ulteriori informazioni sull'API API Keys, consulta la documentazione dell'API API Keys.

Introduzione alle chiavi API

Quando utilizzi una chiave API per l'autenticazione in un'API, la chiave API non identifica un'entità, né fornisce informazioni di autorizzazione. Pertanto, la richiesta non utilizza Identity and Access Management (IAM) per verificare se il chiamante dispone dell'autorizzazione per eseguire l'operazione richiesta.

La chiave API associa la richiesta a un progetto Google Cloud ai fini della fatturazione e delle quote. Poiché le chiavi API non identificano il chiamante, vengono spesso utilizzate per accedere a risorse o dati pubblici.

Molte API Google Cloud non accettano chiavi API per l'autenticazione. Consulta la documentazione sull'autenticazione del servizio o dell'API che vuoi utilizzare per determinare se supporta le chiavi API.

Una chiave API include i seguenti componenti, che puoi utilizzare per gestire e utilizzare la chiave:

String
La stringa della chiave API è una stringa criptata, ad esempio AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe. Quando usi una chiave API per l'autenticazione, usa sempre la stringa della chiave. Le chiavi API non hanno un file JSON associato.
ID
L'ID chiave API viene utilizzato dagli strumenti amministrativi di Google Cloud per identificare in modo univoco la chiave. L'ID chiave non può essere utilizzato per l'autenticazione. L'ID chiave è disponibile nell'URL della pagina di modifica della chiave nella console Google Cloud. Puoi anche recuperare l'ID chiave utilizzando Google Cloud CLI per elencare le chiavi nel tuo progetto.
Nome visualizzato
Il nome visualizzato è un nome descrittivo facoltativo della chiave, che puoi impostare quando crei o aggiorni la chiave.

Per gestire le chiavi API, devi disporre del ruolo Amministratore chiavi API (roles/serviceusage.apiKeysAdmin) nel progetto.

Prima di iniziare

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

Console

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

gcloud

Nella console Google Cloud, attiva Cloud Shell.

Attiva Cloud Shell

Nella parte inferiore della console Google Cloud viene avviata una sessione di Cloud Shell che mostra un prompt della riga di comando. Cloud Shell è un ambiente shell con Google Cloud CLI già installato e con valori già impostati per il progetto attuale. L'inizializzazione della sessione può richiedere alcuni secondi.

Java

Per utilizzare gli Java esempi in questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

  1. Installa Google Cloud CLI.
  2. Per initialize gcloud CLI, esegui questo comando:

    gcloud init
  3. Crea credenziali di autenticazione locali per il tuo Account Google:

    gcloud auth application-default login

Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale nella documentazione sull'autenticazione di Google Cloud.

Python

Per utilizzare gli Python esempi in questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

  1. Installa Google Cloud CLI.
  2. Per initialize gcloud CLI, esegui questo comando:

    gcloud init
  3. Crea credenziali di autenticazione locali per il tuo Account Google:

    gcloud auth application-default login

Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale nella documentazione sull'autenticazione di Google Cloud.

REST

Per utilizzare gli esempi di API REST in questa pagina in un ambiente di sviluppo locale, utilizzi le credenziali che fornisci a gcloud CLI.

    Installa Google Cloud CLI, quindi initialize eseguendo questo comando:

    gcloud init

Per maggiori informazioni, consulta Autenticazione per l'utilizzo di REST nella documentazione sull'autenticazione di Google Cloud.

crea una chiave API

Per creare una chiave API, utilizza una delle seguenti opzioni:

Console

  1. Nella console Google Cloud, vai alla pagina Credenziali:

    Vai a credenziali

  2. Fai clic su Crea credenziali, quindi seleziona Chiave API dal menu.

    La finestra di dialogo Chiave API creata mostra la stringa per la chiave appena creata.

gcloud

Puoi utilizzare il comando gcloud beta services api-keys create per creare una chiave API.

Sostituisci DISPLAY_NAME con un nome descrittivo della chiave.

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

Java

Per eseguire questo esempio, devi installare la libreria client di 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

Per eseguire questo esempio, devi installare la libreria client delle chiavi 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

Per creare una chiave API, devi utilizzare il metodo keys.create. Questa richiesta restituisce un'operazione a lunga esecuzione; devi eseguire il polling dell'operazione per ottenere le informazioni per la nuova chiave.

Sostituisci i seguenti valori:

  • DISPLAY_NAME: facoltativo. Un nome descrittivo della chiave.
  • PROJECT_ID: l'ID o il nome del tuo progetto 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"

Per ulteriori informazioni sulla creazione di chiavi API mediante l'API REST, consulta Creazione di una chiave API nella documentazione dell'API Chiavi API.

Copia la stringa della chiave e tienila al sicuro. A meno che tu non stia utilizzando una chiave di test che intendi eliminare in seguito, aggiungi limitazioni relative alle chiavi API e delle applicazioni.

Usa una chiave API

Se un'API supporta l'uso di chiavi API, puoi utilizzare le chiavi API per autenticare quell'API. Puoi utilizzare le chiavi API con le richieste REST e con le librerie client che le supportano.

Utilizzo di una chiave API con REST

Puoi passare la chiave API in una chiamata API REST come parametro di query con il formato seguente. Sostituisci API_KEY con la stringa della chiave API della tua chiave API.

Ad esempio, per passare una chiave API per una richiesta API Cloud Natural Language per documents.analyzeEntities:

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

In alternativa, puoi utilizzare l'intestazione x-goog-api-key per trasmettere la chiave. Questa intestazione deve essere utilizzata con le richieste gRPC.

curl -X POST \
    -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"

Utilizzo di una chiave API con librerie client

Il supporto della libreria client per le chiavi API è specifico per ogni lingua.

Python

In questo esempio viene utilizzata l'API Cloud Natural Language, che supporta le chiavi API per l'autenticazione, per dimostrare come fornire una chiave API alla libreria.

Per eseguire questo esempio, devi installare la libreria client di Natural Language e la libreria client delle chiavi 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")

Proteggere una chiave API

Quando utilizzi chiavi API nelle tue applicazioni, assicurati che siano protette sia durante l'archiviazione che la trasmissione. L'esposizione pubblica delle chiavi API può comportare addebiti imprevisti sul tuo account. Per proteggere le tue chiavi API, segui queste best practice:

  • Aggiungi restrizioni relative alle chiavi API alla chiave.

    Aggiungendo limitazioni, puoi limitare i modi in cui una chiave API può essere utilizzata, riducendo l'impatto di una chiave API compromessa.

  • Elimina le chiavi API non necessarie per ridurre al minimo l'esposizione agli attacchi.

  • Ricrea periodicamente le chiavi API.

    Creare periodicamente nuove chiavi API, eliminare le vecchie chiavi e aggiornare le applicazioni in modo che utilizzino le nuove chiavi API.

Applica limitazioni relative alle chiavi API

Per impostazione predefinita, le chiavi API non sono limitate. Le chiavi senza restrizioni non sono sicure perché possono essere utilizzate da chiunque, ovunque. Per le applicazioni di produzione, devi impostare sia restrizioni delle applicazioni che restrizioni API.

Aggiungi limitazioni delle applicazioni

Le limitazioni delle applicazioni specificano i siti web, gli indirizzi IP o le app che possono utilizzare una chiave API.

Puoi applicare un solo tipo di limitazione delle applicazioni alla volta. Scegli il tipo di restrizione in base al tuo tipo di applicazione:

Opzione Tipo di applicazione Note
Referrer HTTP Applicazioni web Specifica i siti web che possono utilizzare la chiave.
Indirizzi IP Applicazioni richiamate da server specifici Specifica i server o i cron job che possono utilizzare la chiave.
App per Android App Android Specifica l'applicazione Android che può utilizzare la chiave.
App per iOS Applicazioni iOS Specifica i bundle iOS che possono utilizzare la chiave.

Referrer HTTP

Per limitare i siti web che possono utilizzare la tua chiave API, aggiungi una o più limitazioni dei referrer HTTP.

Puoi sostituire un carattere jolly (*) per il sottodominio o il percorso, ma non puoi inserire un carattere jolly al centro dell'URL. Ad esempio, *.example.com è valido e accetta tutti i siti che terminano con .example.com. Tuttavia, mysubdomain*.example.com non è una limitazione valida.

I numeri di porta possono essere inclusi nelle restrizioni relative ai referrer HTTP. Se includi un numero di porta, vengono soddisfatte solo le richieste che lo utilizzano. Se non specifichi un numero di porta, verranno soddisfatte le richieste provenienti da qualsiasi numero di porta.

Puoi aggiungere fino a 1200 referrer HTTP a una chiave API.

La tabella seguente mostra alcuni scenari di esempio e limitazioni del browser:

Scenario Restrizioni
Consenti un URL specifico Aggiungi un URL con un percorso esatto. Ad esempio:
www.example.com/path
www.example.com/path/path

Alcuni browser implementano un criterio relativo al referrer che invia solo l'URL di origine per le richieste multiorigine. Gli utenti di questi browser non possono utilizzare chiavi con restrizioni URL specifiche della pagina.

Consenti qualsiasi URL nel tuo sito Devi impostare due URL nell'elenco allowedReferers.
  1. URL per il dominio, senza sottodominio, e con un carattere jolly per il percorso. Ad esempio:
    example.com/*
  2. Un secondo URL che include un carattere jolly per il sottodominio e un carattere jolly per il percorso. Ad esempio:
    *.example.com/*
Consenti qualsiasi URL in un singolo sottodominio o dominio semplice

Devi impostare due URL nell'elenco allowedReferers per consentire un intero dominio:

  1. URL del dominio, senza barra finale. Ad esempio:
    www.example.com
    sub.example.com
    example.com
  2. Un secondo URL per il dominio che include un carattere jolly per il percorso. Ad esempio:
    www.example.com/*
    sub.example.com/*
    example.com/*

Per limitare la chiave API a siti web specifici, utilizza una delle seguenti opzioni:

Console

  1. Nella console Google Cloud, vai alla pagina Credenziali:

    Vai a credenziali

  2. Fai clic sul nome della chiave API che vuoi limitare.

  3. Nella sezione Restrizioni delle applicazioni, seleziona Referrer HTTP.

  4. Per ogni restrizione che vuoi aggiungere, fai clic su Aggiungi un elemento, inserisci la restrizione e fai clic su Fine.

  5. Fai clic su Salva per salvare le modifiche e tornare all'elenco delle chiavi API.

gcloud

  1. Recupera l'ID della chiave che vuoi limitare.

    L'ID non corrisponde al nome visualizzato o alla stringa della chiave. Puoi ottenere l'ID utilizzando il comando gcloud services api-keys list per elencare le chiavi nel tuo progetto.

  2. Utilizza il comando gcloud beta services api-keys update per aggiungere limitazioni dei referrer HTTP a una chiave API.

    Sostituisci i seguenti valori:

    • KEY_ID: l'ID della chiave che vuoi limitare.
    • ALLOWED_REFERRER_1: la limitazione relativa ai referrer HTTP.

      Puoi aggiungere tutte le restrizioni che vuoi: utilizza le virgole per separarle. Devi fornire tutte le restrizioni del referrer con il comando di aggiornamento. Le restrizioni fornite per il referrer sostituiscono tutte le restrizioni del referrer presenti sulla chiave.

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

Java

Per eseguire questo esempio, devi installare la libreria client di 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

Per eseguire questo esempio, devi installare la libreria client delle chiavi 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. Recupera l'ID della chiave che vuoi limitare.

    L'ID non corrisponde al nome visualizzato o alla stringa della chiave. Puoi ottenere l'ID utilizzando il metodo keys.list. L'ID è elencato nel campo uid della risposta.

    Sostituisci PROJECT_ID con l'ID o il nome del tuo progetto 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. Utilizza il metodo keys.patch per aggiungere limitazioni dei referrer HTTP alla chiave API.

    Questa richiesta restituisce un'operazione a lunga esecuzione; devi eseguire il polling dell'operazione per sapere quando viene completata e ottenere lo stato dell'operazione.

    Sostituisci i seguenti valori:

    • ALLOWED_REFERRER_1: la limitazione relativa ai referrer HTTP.

      Puoi aggiungere tutte le restrizioni che vuoi: utilizza le virgole per separarle. Devi fornire tutte le limitazioni relative ai referrer con la richiesta. Le limitazioni relative ai referrer fornite sostituiscono tutte le restrizioni relative ai referrer presenti sulla chiave.

    • PROJECT_ID: il nome o l'ID del tuo progetto Google Cloud.

    • KEY_ID: l'ID della chiave che vuoi limitare.

    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"
    

Per ulteriori informazioni sull'aggiunta di restrizioni dei referrer HTTP a una chiave utilizzando l'API REST, consulta Aggiunta di limitazioni del browser nella documentazione dell'API API Keys.

Indirizzi IP

Puoi specificare uno o più indirizzi IP dei chiamanti, ad esempio un server web o un cron job, a cui è consentito utilizzare la tua chiave API. Puoi specificare gli indirizzi IP in uno dei seguenti formati:

  • IPv4 (198.51.100.1)
  • IPv6 (2001:db8::1)
  • Una subnet che utilizza la notazione CIDR (198.51.100.0/24, 2001:db8::/64)

L'utilizzo di localhost non è supportato per le limitazioni del server.

Per limitare la chiave API a indirizzi IP specifici, utilizza una delle seguenti opzioni:

Console

  1. Nella console Google Cloud, vai alla pagina Credenziali:

    Vai a credenziali

  2. Fai clic sul nome della chiave API che vuoi limitare.

  3. Nella sezione Restrizioni delle applicazioni, seleziona Indirizzi IP.

  4. Per ogni indirizzo IP che vuoi aggiungere, fai clic su Aggiungi un elemento, inserisci l'indirizzo e fai clic su Fine.

  5. Fai clic su Salva per salvare le modifiche e tornare all'elenco delle chiavi API.

gcloud

  1. Recupera l'ID della chiave che vuoi limitare.

    L'ID non corrisponde al nome visualizzato o alla stringa della chiave. Puoi ottenere l'ID utilizzando il comando gcloud services api-keys list per elencare le chiavi nel tuo progetto.

  2. Utilizza il comando gcloud beta services api-keys update per aggiungere restrizioni del server (indirizzo IP) a una chiave API.

    Sostituisci i seguenti valori:

    • KEY_ID: l'ID della chiave che vuoi limitare.
    • ALLOWED_IP_ADDR_1: il tuo indirizzo IP consentito.

      Puoi aggiungere tutti gli indirizzi IP necessari; utilizza le virgole per separare gli indirizzi.

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

Java

Per eseguire questo esempio, devi installare la libreria client di 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

Per eseguire questo esempio, devi installare la libreria client delle chiavi 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. Recupera l'ID della chiave che vuoi limitare.

    L'ID non corrisponde al nome visualizzato o alla stringa della chiave. Puoi ottenere l'ID utilizzando il metodo keys.list. L'ID è elencato nel campo uid della risposta.

    Sostituisci PROJECT_ID con l'ID o il nome del tuo progetto 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. Utilizza il metodo keys.patch per aggiungere restrizioni del server (indirizzo IP) a una chiave API.

    Questa richiesta restituisce un'operazione a lunga esecuzione; devi eseguire il polling dell'operazione per sapere quando viene completata e ottenere lo stato dell'operazione.

    Sostituisci i seguenti valori:

    • ALLOWED_IP_ADDR_1: il tuo indirizzo IP consentito.

      Puoi aggiungere tutti gli indirizzi IP necessari; utilizza le virgole per separare le restrizioni. Devi fornire tutti gli indirizzi IP con la richiesta. Le restrizioni per i referrer fornite sostituiscono tutte le restrizioni esistenti relative agli indirizzi IP per la chiave.

    • PROJECT_ID: il nome o l'ID del tuo progetto Google Cloud.

    • KEY_ID: l'ID della chiave che vuoi limitare.

    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"
    

Per ulteriori informazioni sull'aggiunta di limitazioni degli indirizzi IP a una chiave utilizzando l'API REST, consulta Aggiunta di limitazioni del server nella documentazione dell'API API Keys.

App per Android

Puoi limitare l'utilizzo di una chiave API a specifiche app per Android. Devi fornire il nome del pacchetto e l'impronta digitale del certificato SHA-1 da 20 byte per ogni app.

Quando utilizzi la chiave API in una richiesta, devi specificare il nome del pacchetto e l'impronta digitale del certificato utilizzando le seguenti intestazioni HTTP:

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

Per limitare la chiave API a una o più app per Android, utilizza una delle seguenti opzioni:

Console

  1. Nella console Google Cloud, vai alla pagina Credenziali:

    Vai a credenziali

  2. Fai clic sul nome della chiave API che vuoi limitare.

  3. Nella sezione Limitazioni delle applicazioni, seleziona App Android.

  4. Per ogni app per Android che vuoi aggiungere, fai clic su Aggiungi un elemento e inserisci il nome del pacchetto e l'impronta digitale del certificato SHA-1, quindi fai clic su Fine.

  5. Fai clic su Salva per salvare le modifiche e tornare all'elenco delle chiavi API.

gcloud

  1. Recupera l'ID della chiave che vuoi limitare.

    L'ID non corrisponde al nome visualizzato o alla stringa della chiave. Puoi ottenere l'ID utilizzando il comando gcloud services api-keys list per elencare le chiavi nel tuo progetto.

  2. Usa il comando gcloud beta services api-keys update per specificare le app per Android che possono utilizzare una chiave API.

    Sostituisci i seguenti valori:

    • KEY_ID: l'ID della chiave che vuoi limitare.
    • SHA1_FINGERPRINT e PACKAGE_NAME: le informazioni per un'app per Android che può utilizzare la chiave.

      Puoi aggiungere tutte le app che vuoi; utilizza altri flag --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

Per eseguire questo esempio, devi installare la libreria client di 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

Per eseguire questo esempio, devi installare la libreria client delle chiavi 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. Recupera l'ID della chiave che vuoi limitare.

    L'ID non corrisponde al nome visualizzato o alla stringa della chiave. Puoi ottenere l'ID utilizzando il metodo keys.list. L'ID è elencato nel campo uid della risposta.

    Sostituisci PROJECT_ID con l'ID o il nome del tuo progetto 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. Usa il metodo keys.patch per specificare le app per Android che possono utilizzare una chiave API.

    Questa richiesta restituisce un'operazione a lunga esecuzione; devi eseguire il polling dell'operazione per sapere quando viene completata e ottenere lo stato dell'operazione.

    Sostituisci i seguenti valori:

    • SHA1_FINGERPRINT_1 e PACKAGE_NAME_1: le informazioni per un'app per Android che può utilizzare la chiave.

      Puoi aggiungere le informazioni per tutte le app necessarie; utilizza le virgole per separare gli oggetti AndroidApplication. Devi fornire la richiesta a tutte le applicazioni; le applicazioni fornite sostituiscono eventuali applicazioni consentite esistenti nella chiave.

    • PROJECT_ID: il nome o l'ID del tuo progetto Google Cloud.

    • KEY_ID: l'ID della chiave che vuoi limitare.

    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"
    

Per ulteriori informazioni sull'aggiunta di limitazioni delle app per Android a una chiave tramite l'API REST, consulta Aggiungere limitazioni per Android nella documentazione dell'API Chiavi API.

App per iOS

Puoi limitare l'utilizzo di una chiave API a specifiche app per iOS fornendo l'ID bundle di ogni app.

Quando utilizzi la chiave API in una richiesta, devi specificare l'ID pacchetto tramite l'intestazione HTTP X-Ios-Bundle-Identifier.

Per limitare la chiave API a una o più app per iOS, utilizza una delle seguenti opzioni:

Console

  1. Nella console Google Cloud, vai alla pagina Credenziali:

    Vai a credenziali

  2. Fai clic sul nome della chiave API che vuoi limitare.

  3. Nella sezione Restrizioni delle applicazioni, seleziona App per iOS.

  4. Per ogni app per iOS che vuoi aggiungere, fai clic su Aggiungi un articolo e inserisci l'ID pacchetto, quindi fai clic su Fine.

  5. Fai clic su Salva per salvare le modifiche e tornare all'elenco delle chiavi API.

gcloud

  1. Recupera l'ID della chiave che vuoi limitare.

    L'ID non corrisponde al nome visualizzato o alla stringa della chiave. Puoi ottenere l'ID utilizzando il comando gcloud services api-keys list per elencare le chiavi nel tuo progetto.

  2. Usa il metodo gcloud beta services api-keys update per specificare le app per iOS che possono utilizzare la chiave.

    Sostituisci i seguenti valori:

    • KEY_ID: l'ID della chiave che vuoi limitare.
    • ALLOWED_BUNDLE_ID: l'ID bundle di un'app per iOS per cui vuoi consentire l'utilizzo di questa chiave API.

      Puoi aggiungere tutti gli ID pacchetto necessari; utilizza le virgole per separare gli ID.

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

Java

Per eseguire questo esempio, devi installare la libreria client di 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

Per eseguire questo esempio, devi installare la libreria client delle chiavi 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. Recupera l'ID della chiave che vuoi limitare.

    L'ID non corrisponde al nome visualizzato o alla stringa della chiave. Puoi ottenere l'ID utilizzando il metodo keys.list. L'ID è elencato nel campo uid della risposta.

    Sostituisci PROJECT_ID con l'ID o il nome del tuo progetto 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. Usa il metodo keys.patch per specificare le app per iOS che possono utilizzare una chiave API.

    Questa richiesta restituisce un'operazione a lunga esecuzione; devi eseguire il polling dell'operazione per sapere quando viene completata e ottenere lo stato dell'operazione.

    Sostituisci i seguenti valori:

    • ALLOWED_BUNDLE_ID: l'ID pacchetto di un'app per iOS che può utilizzare la chiave.

      Puoi aggiungere le informazioni per tutte le app di cui hai bisogno; utilizza le virgole per separare gli ID pacchetto. Devi fornire tutti gli ID pacchetto con la richiesta. Gli ID pacchetto forniti sostituiscono eventuali applicazioni consentite esistenti nella chiave.

    • PROJECT_ID: il nome o l'ID del tuo progetto Google Cloud.

    • KEY_ID: l'ID della chiave che vuoi limitare.

    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"
    

Per ulteriori informazioni sull'aggiunta di limitazioni per le app per iOS a una chiave utilizzando l'API REST, consulta Aggiunta di restrizioni iOS nella documentazione dell'API Chiavi API.

Aggiungi limitazioni API

Le restrizioni delle API specificano le API che è possibile chiamare usando la chiave API.

Per aggiungere limitazioni delle API, utilizza una delle seguenti opzioni:

Console

  1. Nella console Google Cloud, vai alla pagina Credenziali:

    Vai a credenziali

  2. Fai clic sul nome della chiave API che vuoi limitare.

  3. Nella sezione Restrizioni API, fai clic su Limita chiave.

  4. Seleziona tutte le API alle quali accederà la tua chiave API.

  5. Fai clic su Salva per salvare le modifiche e tornare all'elenco delle chiavi API.

gcloud

  1. Recupera l'ID della chiave che vuoi limitare.

    L'ID non corrisponde al nome visualizzato o alla stringa della chiave. Puoi ottenere l'ID utilizzando il comando gcloud services api-keys list per elencare le chiavi nel tuo progetto.

  2. Utilizza il comando gcloud beta services api-keys update per specificare in quali servizi è possibile utilizzare una chiave API per l'autenticazione.

    Sostituisci i seguenti valori:

    • KEY_ID: l'ID della chiave che vuoi limitare.
    • SERVICE_1, SERVICE_2...: I nomi dei servizi delle API a cui è possibile utilizzare la chiave per accedere.

      Devi fornire tutti i nomi dei servizi con il comando update. I nomi dei servizi forniti sostituiscono eventuali servizi esistenti nella chiave.

    Puoi trovare il nome del servizio cercando l'API nella dashboard delle API. I nomi dei servizi sono stringhe come bigquery.googleapis.com.

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

Java

Per eseguire questo esempio, devi installare la libreria client di 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

Per eseguire questo esempio, devi installare la libreria client delle chiavi 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. Recupera l'ID della chiave che vuoi limitare.

    L'ID non corrisponde al nome visualizzato o alla stringa della chiave. Puoi ottenere l'ID utilizzando il metodo keys.list. L'ID è elencato nel campo uid della risposta.

    Sostituisci PROJECT_ID con l'ID o il nome del tuo progetto 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. Utilizza il metodo keys.patch per specificare i servizi per cui è possibile utilizzare una chiave API per l'autenticazione.

    Questa richiesta restituisce un'operazione a lunga esecuzione; devi eseguire il polling dell'operazione per sapere quando viene completata e ottenere lo stato dell'operazione.

    Sostituisci i seguenti valori:

    • SERVICE_1, SERVICE_2...: I nomi dei servizi delle API a cui è possibile utilizzare la chiave per accedere.

      Con la richiesta devi fornire tutti i nomi dei servizi. I nomi dei servizi forniti sostituiscono eventuali servizi esistenti nella chiave.

      Puoi trovare il nome del servizio cercando l'API nella dashboard delle API. I nomi dei servizi sono stringhe come bigquery.googleapis.com.

    • PROJECT_ID: il nome o l'ID del tuo progetto Google Cloud.

    • KEY_ID: l'ID della chiave che vuoi limitare.

    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"
    

Per ulteriori informazioni sull'aggiunta di limitazioni API a una chiave utilizzando l'API REST, consulta Aggiunta di restrizioni API nella documentazione dell'API Chiavi API.

Recupera le informazioni sul progetto da una stringa chiave

Puoi determinare a quale progetto Google Cloud è associata una chiave API dalla relativa stringa.

Sostituisci KEY_STRING con la stringa chiave per la quale hai bisogno delle informazioni sul progetto.

gcloud

Puoi utilizzare il comando gcloud beta services api-keys lookup per ottenere l'ID progetto da una stringa della chiave.

 gcloud beta services api-keys lookup KEY_STRING
 

Java

Per eseguire questo esempio, devi installare la libreria client di 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

Per eseguire questo esempio, devi installare la libreria client delle chiavi 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

Utilizzerai il metodo lookupKey per ottenere l'ID progetto da una stringa chiave.

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"

Annullamento eliminazione di una chiave API

Se elimini una chiave API per errore, puoi annullarne l'eliminazione (ripristinarla) entro 30 giorni dall'eliminazione della chiave. Dopo 30 giorni, non potrai annullare l'eliminazione della chiave API.

Console

  1. Nella console Google Cloud, vai alla pagina Credenziali:

    Vai a credenziali

  2. Fai clic su Ripristina credenziali eliminate.

  3. Trova la chiave API eliminata di cui vuoi annullare l'eliminazione e fai clic su Ripristina.

    L'annullamento dell'eliminazione di una chiave API potrebbe richiedere alcuni minuti per propagarsi. Dopo la propagazione, la chiave API non eliminata viene visualizzata nell'elenco delle chiavi API.

gcloud

  1. Recupera l'ID della chiave di cui vuoi annullare l'eliminazione.

    L'ID non corrisponde al nome visualizzato o alla stringa della chiave. Puoi ottenere l'ID utilizzando il comando gcloud services api-keys list --show-deleted per elencare le chiavi eliminate nel tuo progetto.

  2. Utilizza il comando gcloud beta services api-keys undelete per annullare l'eliminazione di una chiave API.

    gcloud beta services api-keys undelete KEY_ID
    

    Sostituisci i seguenti valori:

    • KEY_ID: l'ID della chiave di cui vuoi annullare l'eliminazione.

REST

  1. Recupera l'ID della chiave di cui vuoi annullare l'eliminazione.

    L'ID non corrisponde al nome visualizzato o alla stringa della chiave. Puoi ottenere l'ID utilizzando il metodo keys.list, con il parametro di query showDeleted impostato su true. L'ID chiave è elencato nel campo uid della risposta.

    Sostituisci PROJECT_ID con l'ID o il nome del tuo progetto 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. Utilizza il metodo di undelete per annullare l'eliminazione della chiave 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"
    

    Questa richiesta restituisce un'operazione a lunga esecuzione; devi eseguire il polling dell'operazione per sapere quando viene completata e ottenere lo stato dell'operazione.

    Sostituisci i seguenti valori:

    • PROJECT_ID: il nome o l'ID del tuo progetto Google Cloud.
    • KEY_ID: l'ID della chiave che vuoi limitare.

Operazioni a lunga esecuzione del sondaggio

I metodi API Chiavi API utilizzano operazioni a lunga esecuzione. Se utilizzi l'API REST per creare e gestire le chiavi API, viene restituito un oggetto operazione dalla richiesta iniziale di metodo. Dovrai usare il nome dell'operazione per eseguire il polling dell'operazione a lunga esecuzione. Al completamento della richiesta a lunga esecuzione, il polling dell'operazione restituisce i dati dalla richiesta a lunga esecuzione.

Per eseguire il polling di un'operazione dell'API API Keys a lunga esecuzione, utilizza il metodo operations.get.

Sostituisci OPERATION_NAME con il nome dell'operazione restituito dall'operazione a lunga esecuzione. Ad esempio, 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"

Limiti delle chiavi API

Puoi creare fino a 300 chiavi API per progetto. Questo limite è un limite del sistema e non può essere modificato utilizzando una richiesta di aumento della quota.

Se sono necessarie più chiavi API, devi utilizzare più di un progetto.

Passaggi successivi