Faça a gestão das chaves da API

Esta página descreve como criar, editar e restringir chaves da API. Para obter informações sobre como usar chaves de API para aceder às APIs Google, consulte o artigo Use chaves de API para aceder às APIs.

Introdução às chaves da API

Existem dois tipos de chaves da API: chaves da API padrão e chaves da API que foram associadas a uma conta de serviço.

Chaves da API padrão

As chaves da API padrão oferecem uma forma de associar um pedido a um projeto para fins de faturação e quotas. Quando usa uma chave da API padrão (uma chave da API que não foi associada a uma conta de serviço) para aceder a uma API, a chave da API não identifica um principal. Sem um principal, o pedido não pode usar a gestão de identidade e de acesso (IAM) para verificar se o autor da chamada tem autorização para realizar a operação pedida.

As chaves da API padrão podem ser usadas com qualquer API que aceite chaves da API, a menos que tenham sido adicionadas restrições da API à chave. Não é possível usar chaves da API padrão com serviços que não aceitam chaves da API, incluindo no modo expresso.

Chaves da API associadas a uma conta de serviço

As chaves de API associadas a uma conta de serviço fornecem a identidade e a autorização da conta de serviço a um pedido. Quando usa uma chave da API que foi associada a uma conta de serviço para aceder a uma API, o seu pedido é processado como se tivesse usado a conta de serviço associada para fazer o pedido.

A única API que suporta chaves da API associadas é a aiplatform.googleapis.com.

A associação de chaves a uma conta de serviço é impedida por uma restrição da política da organização predefinida. Para alterar esta opção, consulte o artigo Ative a associação de chaves a contas de serviço.

Componentes da chave da API

Uma chave da API tem os seguintes componentes, que lhe permitem gerir e usar a chave:

String
A cadeia da chave da API é uma cadeia encriptada, por exemplo, AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe. Quando usa uma chave da API para aceder a uma API, usa sempre a string da chave. As chaves da API não têm um ficheiro JSON associado.
ID
O ID da chave da API é usado pelas Google Cloud ferramentas administrativas para identificar a chave de forma exclusiva. Não é possível usar o ID da chave para aceder às APIs. Pode encontrar o ID da chave no URL da página de edição da chave na Google Cloud consola. Também pode obter o ID da chave através da CLI do Google Cloud para listar as chaves no seu projeto.
Nome a apresentar
O nome a apresentar é um nome descritivo opcional para a chave, que pode definir quando cria ou atualiza a chave.
Conta de serviço associada
As chaves de API associadas a uma conta de serviço incluem o endereço de email da conta de serviço.

Antes de começar

Conclua as seguintes tarefas para usar os exemplos nesta página.

Configure a autenticação

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

In the Google Cloud console, activate Cloud Shell.

Activate Cloud Shell

At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

C++

Para usar os C++ exemplos nesta página num ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e, em seguida, configure as Credenciais predefinidas da aplicação com as suas credenciais de utilizador.

  1. Install the Google Cloud CLI.

  2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  3. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

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

Para mais informações, consulte Configure o ADC para um ambiente de desenvolvimento local na Google Cloud documentação de autenticação.

Java

Para usar os Java exemplos nesta página num ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e, em seguida, configure as Credenciais predefinidas da aplicação com as suas credenciais de utilizador.

  1. Install the Google Cloud CLI.

  2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  3. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

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

Para mais informações, consulte Configure o ADC para um ambiente de desenvolvimento local na Google Cloud documentação de autenticação.

Python

Para usar os Python exemplos nesta página num ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e, em seguida, configure as Credenciais predefinidas da aplicação com as suas credenciais de utilizador.

  1. Install the Google Cloud CLI.

  2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  3. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

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

Para mais informações, consulte Configure o ADC para um ambiente de desenvolvimento local na Google Cloud documentação de autenticação.

REST

Para usar os exemplos da API REST nesta página num ambiente de desenvolvimento local, usa as credenciais que fornece à CLI gcloud.

    Install the Google Cloud CLI.

    If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

Para mais informações, consulte o artigo Autenticar para usar REST na Google Cloud documentação de autenticação.

Funções necessárias

Para obter as autorizações de que precisa para gerir chaves de API, peça ao seu administrador para lhe conceder as seguintes funções da IAM no seu projeto:

Para mais informações sobre a atribuição de funções, consulte o artigo Faça a gestão do acesso a projetos, pastas e organizações.

Também pode conseguir as autorizações necessárias através de funções personalizadas ou outras funções predefinidas.

Ative a vinculação de chaves a contas de serviço

Antes de poder associar uma chave de API a uma conta de serviço, tem de definir a restrição da política da organização constraints/iam.managed.disableServiceAccountApiKeyCreation como false. A alteração da política da organização requer um recurso da organização associado. Os projetos sem uma organização não são suportados.

Para alterar a restrição de política, siga estas instruções.

Consola

  1. Na Google Cloud consola, aceda à página Políticas de organização.

    Aceda às políticas da organização

  2. Mude para a organização, a pasta ou o projeto para o qual quer alterar as políticas.

  3. Na caixa Filtro, introduza Block service e, de seguida, clique no nome do filtro Bloquear associações de chaves da API de contas de serviço.

  4. Clique em Gerir política.

  5. Na secção Origem da política, selecione Substituir política do elemento principal.

  6. Clique em Adicionar uma regra e defina Aplicação como Desativada.

  7. Clique em Concluído.

  8. Opcional: clique em Testar alterações para ver informações sobre como a política proposta pode causar violações ou interrupções da conformidade.

  9. Clique em Definir política.

gcloud

  1. Crie um ficheiro denominado spec.yaml com o seguinte conteúdo:

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

    Indique os seguintes valores:

    • SCOPE: organizations, folders ou projects.

    • SCOPE_ID: consoante SCOPE, o ID da organização, da pasta ou do projeto ao qual a política de organização se aplica.

  2. Execute o seguinte comando gcloud para permitir a associação de chaves de API a contas de serviço:

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

Crie uma chave da API

Para criar uma chave da API, use uma das seguintes opções:

Consola

  1. Na Google Cloud consola, aceda à página Credenciais:

    Aceder a Credenciais

  2. Clique em Criar credenciais e, de seguida, selecione Chave de API no menu.

  3. Opcional: para associar a chave da API a uma conta de serviço, selecione a caixa de verificação Autenticar chamadas da API através de uma conta de serviço e, de seguida, clique em Selecionar uma conta de serviço para selecionar a conta de serviço que quer associar à chave.

    Para mais informações, consulte o artigo Chaves da API associadas a uma conta de serviço.

  4. Adicione restrições à chave da API.

    Restringir as chaves da API é uma prática recomendada. Para mais informações, consulte o artigo Aplique restrições de chaves da API.

  5. Clique em Criar. A caixa de diálogo Chave da API criada apresenta a string da chave criada recentemente.

gcloud

Use o gcloud services api-keys create comando para criar uma chave da API.

Substitua DISPLAY_NAME por um nome descritivo para a chave.

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

Opcional: para associar a chave da API a uma conta de serviço, use gcloud beta em vez disso, com a flag --service-account:

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

Para mais informações, consulte o artigo Chaves da API associadas a uma conta de serviço.

C++

Para executar este exemplo, tem de instalar a biblioteca cliente das chaves da API.

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

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

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

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

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

Java

Para executar este exemplo, tem de instalar a google-cloud-apikeys biblioteca cliente.


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

Para executar este exemplo, tem de instalar a biblioteca cliente das chaves da 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

Use o métodokeys.create para criar uma chave da API. Este pedido devolve uma operação de longa duração. Tem de sondar a operação para obter as informações da nova chave.

Substitua os seguintes valores:

  • DISPLAY_NAME: opcional. Um nome descritivo para a sua chave.
  • PROJECT_ID: o ID ou o nome do seu projeto 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"

Opcional: para associar a chave da API a uma conta de serviço, use o seguinte comando:

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

Para mais informações, consulte o artigo Chaves da API associadas a uma conta de serviço.

Para mais informações sobre a criação de chaves da API através da API REST, consulte o artigo Criar uma chave da API na documentação da API Google Maps API Keys.

Aplique restrições da chave da API

Por predefinição, as chaves da API não têm restrições. As chaves não restritas são inseguras porque podem ser usadas por qualquer pessoa em qualquer lugar. Para aplicações de produção, deve definir restrições de aplicações e restrições de API.

Adicione restrições de aplicações

As restrições de aplicações especificam que Websites, endereços IP ou apps podem usar uma chave da API.

Só pode aplicar um tipo de restrição de aplicação de cada vez. Escolha o tipo de restrição com base no tipo de aplicação:

Opção Tipo de aplicação Notas
Referenciadores HTTP Apps Web Especifica os Websites que podem usar a chave.
Endereços IP Aplicações chamadas por servidores específicos Especifica os servidores ou as tarefas cron que podem usar a chave. Esta é a única restrição disponível se associar a chave da API a uma conta de serviço.
Apps Android Apps para Android Especifica a aplicação Android que pode usar a chave.
Apps iOS Aplicações iOS Especifica os pacotes iOS que podem usar a chave.

Referenciadores HTTP

Para restringir os Websites que podem usar a sua chave da API, adicione uma ou mais restrições de referenciadores HTTP.

Pode substituir um caráter universal (*) pelo subdomínio ou pelo caminho, mas não pode inserir um caráter universal no meio do URL. Por exemplo, *.example.com é válido e aceita todos os sites que terminam em .example.com. No entanto, mysubdomain*.example.com não é uma restrição válida.

Os números de porta podem ser incluídos nas restrições do referenciador HTTP. Se incluir um número de porta, apenas são correspondidos pedidos que usem essa porta. Se não especificar um número da porta, as solicitações de qualquer número da porta são correspondentes.

A tabela seguinte mostra alguns cenários de exemplo e restrições do navegador:

Cenário Restrições
Permita um URL específico Adicione um URL com um caminho exato. Por exemplo:
www.example.com/path
www.example.com/path/path

Alguns navegadores implementam uma política de referenciador que envia apenas o URL de origem para pedidos de origem cruzada. Os utilizadores destes navegadores não podem usar chaves com restrições de URL específicas da página.

Permitir qualquer URL no seu site Tem de definir dois URLs na lista allowedReferers.
  1. URL do domínio, sem um subdomínio e com um caráter universal para o caminho. Por exemplo:
    example.com/*
  2. Um segundo URL que inclui um caráter universal para o subdomínio e um caráter universal para o caminho. Por exemplo:
    *.example.com/*
Permitir qualquer URL num único subdomínio ou domínio simples

Tem de definir dois URLs na lista allowedReferers para permitir um domínio inteiro:

  1. URL do domínio, sem uma barra final. Por exemplo:
    www.example.com
    sub.example.com
    example.com
  2. Um segundo URL para o domínio que inclui um caráter universal para o caminho. Por exemplo:
    www.example.com/*
    sub.example.com/*
    example.com/*

Para restringir a sua chave da API a Websites específicos, use uma das seguintes opções:

Consola

  1. Na Google Cloud consola, aceda à página Credenciais:

    Aceder a Credenciais

  2. Clique no nome da chave de API que quer restringir.

  3. Na secção Restrições de aplicações, selecione Referenciadores HTTP.

  4. Para cada restrição que quer adicionar, clique em Adicionar um item, introduza a restrição e clique em Concluído.

  5. Clique em Guardar para guardar as alterações e voltar à lista de chaves da API.

gcloud

  1. Obtenha o ID da chave que quer restringir.

    O ID não é igual ao nome a apresentar nem à string da chave. Pode obter o ID através do comando gcloud services api-keys list para listar as chaves no seu projeto.

  2. Use o comando gcloud services api-keys update para adicionar restrições de referenciadores HTTP a uma chave da API.

    Substitua os seguintes valores:

    • KEY_ID: o ID da chave que quer restringir.
    • ALLOWED_REFERRER_1: A sua restrição de referenciador HTTP.

      Pode adicionar as restrições necessárias. Use vírgulas para separar as restrições. Tem de fornecer todas as restrições de referenciadores com o comando update. As restrições de referenciadores fornecidas substituem quaisquer restrições de referenciadores existentes na chave.

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

Java

Para executar este exemplo, tem de instalar a google-cloud-apikeys biblioteca cliente.


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

Para executar este exemplo, tem de instalar a biblioteca cliente das chaves da 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. Obtenha o ID da chave que quer restringir.

    O ID não é igual ao nome a apresentar nem à string da chave. Pode obter o ID através do método keys.list. O ID está listado no campo uid da resposta.

    Substitua PROJECT_ID pelo ID ou nome do seu Google Cloud projeto.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. Use o método keys.patch para adicionar restrições de referenciadores HTTP à chave da API.

    Este pedido devolve uma operação de longa duração. Tem de verificar a operação para saber quando esta é concluída e obter o respetivo estado.

    Substitua os seguintes valores:

    • ALLOWED_REFERRER_1: A sua restrição de referenciador HTTP.

      Pode adicionar as restrições necessárias. Use vírgulas para separar as restrições. Tem de fornecer todas as restrições de referenciadores com o pedido. As restrições de referenciadores fornecidas substituem quaisquer restrições de referenciadores existentes na chave.

    • PROJECT_ID: o ID ou o nome do seu projeto Google Cloud .

    • KEY_ID: o ID da chave que quer restringir.

    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"

Para mais informações sobre como adicionar restrições de referenciadores HTTP a uma chave através da API REST, consulte o artigo Adicionar restrições de navegador na documentação da API API Keys.

Moradas IP

Pode especificar um ou mais endereços IP dos autores da chamada, como um servidor Web ou uma tarefa cron, que têm autorização para usar a sua chave da API. Pode especificar os endereços IP em qualquer um dos seguintes formatos:

  • IPv4 (198.51.100.1)
  • IPv6 (2001:db8::1)
  • Uma sub-rede que usa a notação CIDR (198.51.100.0/24, 2001:db8::/64)

A utilização do localhost não é suportada para restrições do servidor.

Para restringir a sua chave da API a endereços IP específicos, use uma das seguintes opções:

Consola

  1. Na Google Cloud consola, aceda à página Credenciais:

    Aceder a Credenciais

  2. Clique no nome da chave de API que quer restringir.

  3. Na secção Restrições de aplicações, selecione Endereços IP.

  4. Para cada endereço IP que quer adicionar, clique em Adicionar um item, introduza o endereço e clique em Concluído.

  5. Clique em Guardar para guardar as alterações e voltar à lista de chaves da API.

gcloud

  1. Obtenha o ID da chave que quer restringir.

    O ID não é igual ao nome a apresentar nem à string da chave. Pode obter o ID através do comando gcloud services api-keys list para listar as chaves no seu projeto.

  2. Use o comando gcloud services api-keys update para adicionar restrições de servidor (endereço IP) a uma chave da API.

    Substitua os seguintes valores:

    • KEY_ID: o ID da chave que quer restringir.
    • ALLOWED_IP_ADDR_1: o seu endereço IP permitido.

      Pode adicionar todos os endereços IP necessários. Use vírgulas para separar os endereços.

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

Java

Para executar este exemplo, tem de instalar a google-cloud-apikeys biblioteca cliente.


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

Para executar este exemplo, tem de instalar a biblioteca cliente das chaves da 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. Obtenha o ID da chave que quer restringir.

    O ID não é igual ao nome a apresentar nem à string da chave. Pode obter o ID através do método keys.list. O ID está listado no campo uid da resposta.

    Substitua PROJECT_ID pelo ID Google Cloud ou nome do projeto.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. Use o método keys.patch para adicionar restrições de servidor (endereço IP) a uma chave da API.

    Este pedido devolve uma operação de longa duração. Tem de verificar a operação para saber quando esta é concluída e obter o respetivo estado.

    Substitua os seguintes valores:

    • ALLOWED_IP_ADDR_1: o seu endereço IP permitido.

      Pode adicionar todos os endereços IP necessários. Use vírgulas para separar as restrições. Tem de fornecer todos os endereços IP com o pedido. As restrições de referenciadores fornecidas substituem quaisquer restrições de endereços IP existentes na chave.

    • PROJECT_ID: o ID ou o nome do seu projeto Google Cloud .

    • KEY_ID: o ID da chave que quer restringir.

    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"

Para mais informações sobre como adicionar restrições de endereço IP a uma chave através da API REST, consulte o artigo Adicionar restrições de servidor na documentação da API API Keys.

Apps Android

Pode restringir a utilização de uma chave da API a apps Android específicas. Tem de indicar o nome do pacote e a impressão digital do certificado SHA-1 de 20 bytes para cada app.

Quando usa a chave de API num pedido, tem de especificar o nome do pacote e a impressão digital do certificado através dos seguintes cabeçalhos HTTP:

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

Para restringir a sua chave da API a uma ou mais apps Android, use uma das seguintes opções:

Consola

  1. Na Google Cloud consola, aceda à página Credenciais:

    Aceder a Credenciais

  2. Clique no nome da chave de API que quer restringir.

  3. Na secção Restrições de aplicações, selecione Apps Android.

  4. Para cada app Android que quer adicionar, clique em Adicionar um item e introduza o nome do pacote e a impressão digital do certificado SHA-1. Em seguida, clique em Concluído.

  5. Clique em Guardar para guardar as alterações e voltar à lista de chaves da API.

gcloud

  1. Obtenha o ID da chave que quer restringir.

    O ID não é igual ao nome a apresentar nem à string da chave. Pode obter o ID através do comando gcloud services api-keys list para listar as chaves no seu projeto.

  2. Use o comando gcloud services api-keys update para especificar as apps Android que podem usar uma chave da API.

    Substitua os seguintes valores:

    • KEY_ID: o ID da chave que quer restringir.
    • SHA1_FINGERPRINT e PACKAGE_NAME: as informações da app para uma app Android que pode usar a chave.

      Pode adicionar as apps necessárias; use flags --allowed-application adicionais.

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

Java

Para executar este exemplo, tem de instalar a google-cloud-apikeys biblioteca cliente.


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

Para executar este exemplo, tem de instalar a biblioteca cliente das chaves da 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. Obtenha o ID da chave que quer restringir.

    O ID não é igual ao nome a apresentar nem à string da chave. Pode obter o ID através do método keys.list. O ID está listado no campo uid da resposta.

    Substitua PROJECT_ID pelo ID ou nome do seu Google Cloud projeto.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. Use o método keys.patch para especificar as apps Android que podem usar uma chave da API.

    Este pedido devolve uma operação de longa duração. Tem de verificar a operação para saber quando esta é concluída e obter o respetivo estado.

    Substitua os seguintes valores:

    • SHA1_FINGERPRINT_1 e PACKAGE_NAME_1: as informações da app para uma app Android que pode usar a chave.

      Pode adicionar as informações para as apps necessárias. Use vírgulas para separar os objetos AndroidApplication. Tem de fornecer todas as aplicações com o pedido; as aplicações fornecidas substituem todas as aplicações permitidas existentes na chave.

    • PROJECT_ID: o ID ou o nome do seu projeto Google Cloud .

    • KEY_ID: o ID da chave que quer restringir.

    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"

Para mais informações sobre como adicionar restrições de apps Android a uma chave através da API REST, consulte a secção Adicionar restrições do Android na documentação da API Keys.

Apps iOS

Pode restringir a utilização de uma chave da API a apps iOS específicas, indicando o ID do pacote de cada app.

Quando usa a chave da API num pedido, tem de especificar o ID do pacote através do cabeçalho HTTP X-Ios-Bundle-Identifier.

Para restringir a sua chave da API a uma ou mais apps iOS, use uma das seguintes opções:

Consola

  1. Na Google Cloud consola, aceda à página Credenciais:

    Aceder a Credenciais

  2. Clique no nome da chave de API que quer restringir.

  3. Na secção Restrições de aplicações, selecione Apps iOS.

  4. Para cada app iOS que quer adicionar, clique em Adicionar um item e introduza o ID do pacote. De seguida, clique em Concluído.

  5. Clique em Guardar para guardar as alterações e voltar à lista de chaves da API.

gcloud

  1. Obtenha o ID da chave que quer restringir.

    O ID não é igual ao nome a apresentar nem à string da chave. Pode obter o ID através do comando gcloud services api-keys list para listar as chaves no seu projeto.

  2. Use o método gcloud services api-keys update para especificar as apps iOS que podem usar a chave.

    Substitua os seguintes valores:

    • KEY_ID: o ID da chave que quer restringir.
    • ALLOWED_BUNDLE_ID: o ID do pacote de uma app iOS que quer poder usar esta chave da API.

      Pode adicionar todos os IDs dos pacotes necessários. Use vírgulas para separar os IDs.

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

Java

Para executar este exemplo, tem de instalar a google-cloud-apikeys biblioteca cliente.


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

Para executar este exemplo, tem de instalar a biblioteca cliente das chaves da 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. Obtenha o ID da chave que quer restringir.

    O ID não é igual ao nome a apresentar nem à string da chave. Pode obter o ID através do método keys.list. O ID está listado no campo uid da resposta.

    Substitua PROJECT_ID pelo ID ou nome do seu Google Cloud projeto.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. Use o método keys.patch para especificar as apps iOS que podem usar uma chave da API.

    Este pedido devolve uma operação de longa duração. Tem de verificar a operação para saber quando esta é concluída e obter o respetivo estado.

    Substitua os seguintes valores:

    • ALLOWED_BUNDLE_ID: O ID do pacote de uma app iOS que pode usar a chave.

      Pode adicionar as informações para todas as apps necessárias. Use vírgulas para separar os IDs dos pacotes. Tem de fornecer todos os IDs dos pacotes com o pedido. Os IDs dos pacotes fornecidos substituem todas as aplicações permitidas existentes na chave.

    • PROJECT_ID: o ID ou o nome do seu projeto Google Cloud .

    • KEY_ID: o ID da chave que quer restringir.

    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"

Para mais informações sobre como adicionar restrições de apps iOS a uma chave através da API REST, consulte o artigo Adicionar restrições de iOS na documentação da API Keys API.

Adicione restrições de API

As restrições da API especificam que APIs podem ser chamadas através da chave da API.

Para adicionar restrições de API, use uma das seguintes opções:

Consola

  1. Na Google Cloud consola, aceda à página Credenciais:

    Aceder a Credenciais

  2. Clique no nome da chave de API que quer restringir.

  3. Na secção Restrições da API, clique em Restringir chave.

  4. Selecione todas as APIs que a sua chave da API vai usar para aceder.

  5. Clique em Guardar para guardar as alterações e voltar à lista de chaves da API.

gcloud

  1. Obtenha o ID da chave que quer restringir.

    O ID não é igual ao nome a apresentar nem à string da chave. Pode obter o ID através do comando gcloud services api-keys list para listar as chaves no seu projeto.

  2. Use o comando gcloud services api-keys update para especificar a que serviços uma chave de API pode ser usada para aceder.

    Substitua os seguintes valores:

    • KEY_ID: o ID da chave que quer restringir.
    • SERVICE_1, SERVICE_2...: Os nomes dos serviços das APIs que a chave pode usar para aceder.

      Tem de indicar todos os nomes dos serviços com o comando de atualização. Os nomes dos serviços indicados substituem os serviços existentes na chave.

    Pode encontrar o nome do serviço pesquisando a API no painel de controlo da API. Os nomes dos serviços são strings como bigquery.googleapis.com.

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

Java

Para executar este exemplo, tem de instalar a google-cloud-apikeys biblioteca cliente.


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

Para executar este exemplo, tem de instalar a biblioteca cliente das chaves da 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. Obtenha o ID da chave que quer restringir.

    O ID não é igual ao nome a apresentar nem à string da chave. Pode obter o ID através do método keys.list. O ID está listado no campo uid da resposta.

    Substitua PROJECT_ID pelo ID ou nome do seu Google Cloud projeto.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. Use o método keys.patch para especificar a que serviços uma chave da API pode ser usada para aceder.

    Este pedido devolve uma operação de execução prolongada. Tem de verificar a operação para saber quando a operação é concluída e obter o estado da operação.

    Substitua os seguintes valores:

    • SERVICE_1, SERVICE_2...: Os nomes dos serviços das APIs que a chave pode usar para aceder.

      Tem de fornecer todos os nomes dos serviços com o pedido. Os nomes dos serviços fornecidos substituem os serviços existentes na chave.

      Pode encontrar o nome do serviço pesquisando a API no painel de controlo da API. Os nomes dos serviços são strings como bigquery.googleapis.com.

    • PROJECT_ID: o ID ou o nome do seu projeto Google Cloud .

    • KEY_ID: o ID da chave que quer restringir.

    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"

Para mais informações sobre como adicionar restrições de API a uma chave através da API REST, consulte o artigo Adicionar restrições de API na documentação da API API Keys.

Receba informações do projeto a partir de uma string de chave

Pode determinar a que Google Cloud projeto uma chave da API está associada a partir da respetiva string.

Substitua KEY_STRING pela string da chave para a qual precisa de informações do projeto.

gcloud

Use o comando gcloud services api-keys lookup para obter o ID do projeto a partir de uma string de chave.

 gcloud services api-keys lookup KEY_STRING
 

Java

Para executar este exemplo, tem de instalar a google-cloud-apikeys biblioteca cliente.


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

Para executar este exemplo, tem de instalar a biblioteca cliente das chaves da 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

Use o lookupKey método para obter o ID do projeto a partir de uma string de chave.

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"

Crie uma cópia de uma chave da API

Se precisar de uma nova chave da API com as mesmas restrições que uma chave da API existente, pode criar uma cópia da chave da API existente. Esta operação cria uma nova chave da API com uma string e um ID de chave únicos, com as restrições da chave da API existente.

A operação de cópia só está disponível na Google Cloud consola. Para usar outros métodos, siga os passos para criar uma chave da API e, em seguida, aplique as mesmas restrições da chave da API à chave da API gerada recentemente.

  1. Na Google Cloud consola, aceda à página Credenciais:

    Aceder a Credenciais

  2. Clique no nome da chave de API que quer copiar.

    É apresentada a página de detalhes da chave de API.

  3. Clique em Criar uma cópia.

  4. Introduza um nome para a nova chave de API e confirme se as restrições estão corretas.

  5. Clique em Criar.

Alterne uma chave da API

Ao rodar periodicamente as chaves da API, pode limitar o impacto de chaves da API comprometidas.

Quando roda uma chave da API, cria uma nova chave com as mesmas restrições que a chave antiga e atualiza as suas aplicações para usarem a nova chave. Depois de todas as suas aplicações serem atualizadas, elimine a chave antiga.

A operação de rotação só está disponível na Google Cloud consola. Para usar outros métodos, siga os passos para criar uma chave da API e, em seguida, aplique as mesmas restrições da chave da API à chave da API gerada recentemente. Depois de atualizar as suas aplicações para usar a nova chave, pode eliminar a chave antiga.

  1. Na Google Cloud consola, aceda à página Credenciais:

    Aceder a Credenciais

  2. Clique no nome da chave da API que quer rodar para abrir a respetiva página de detalhes.

  3. Clique em Alternar chave.

  4. Introduza um nome para a nova chave de API e confirme se as restrições estão corretas.

  5. Clique em Criar.

  6. Copie a string da chave e atualize as suas aplicações para usar a nova string.

  7. Depois de atualizar todas as aplicações para usar a nova chave, regresse à página de detalhes da nova chave. Na secção Chave anterior, clique em Eliminar chave anterior para eliminar a chave antiga.

    Se verificar que eliminou a chave antiga prematuramente, pode anular a eliminação.

Anule a eliminação de uma chave da API

Se eliminar uma chave da API por engano, pode anular a eliminação (restaurar) dessa chave no prazo de 30 dias após a eliminação. Após 30 dias, não pode anular a eliminação da chave da API.

Consola

  1. Na Google Cloud consola, aceda à página Credenciais:

    Aceder a Credenciais

  2. Clique em Restaurar credenciais eliminadas.

  3. Encontre a chave da API eliminada que quer restaurar e clique em Restaurar.

    A anulação da eliminação de uma chave de API pode demorar alguns minutos a propagar-se. Após a propagação, a chave da API não eliminada é apresentada na lista de chaves da API.

gcloud

  1. Obtenha o ID da chave que quer recuperar.

    O ID não é igual ao nome a apresentar nem à string da chave. Pode obter o ID através do comando gcloud services api-keys list --show-deleted para listar as chaves eliminadas no seu projeto.

  2. Use o gcloud services api-keys undelete comando para anular a eliminação de uma chave da API.

    gcloud services api-keys undelete KEY_ID

    Substitua os seguintes valores:

    • KEY_ID: o ID da chave que quer anular a eliminação.

Java

Para executar este exemplo, tem de instalar a google-cloud-apikeys biblioteca cliente.

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

public class UndeleteApiKey {

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

    undeleteApiKey(projectId, keyId);
  }

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

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

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

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

REST

  1. Obtenha o ID da chave que quer recuperar.

    O ID não é igual ao nome a apresentar nem à string da chave. Pode obter o ID através do método keys.list, com o parâmetro de consulta showDeleted definido como true. O ID da chave está indicado no campo uid da resposta.

    Substitua PROJECT_ID pelo ID ou nome do seu Google Cloud projeto.

    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. Use o método undelete para anular a eliminação da chave da 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"

    Este pedido devolve uma operação de longa duração. Tem de verificar a operação para saber quando esta é concluída e obter o respetivo estado.

    Substitua os seguintes valores:

    • PROJECT_ID: o ID ou o nome do seu projeto Google Cloud .
    • KEY_ID: o ID da chave que quer restringir.

Determine o tipo de chave da API

Pode determinar se a chave da API está associada a uma conta de serviço inspecionando a chave.

Consola

  1. Na Google Cloud consola, aceda à página Credenciais:

    Aceder a Credenciais

    Se a chave da API estiver associada a uma conta de serviço, é apresentado o identificador da conta de serviço.

gcloud

  1. Obtenha o ID da chave.

    O ID não é igual ao nome a apresentar nem à string da chave. Pode obter o ID através do comando gcloud services api-keys list para listar as chaves no seu projeto.

  2. Use o comando gcloud services api-keys describe para descrever a chave da API.

    gcloud services api-keys describe KEY_ID

    Se a chave da API estiver associada a uma conta de serviço, o campo serviceAccountEmail é apresentado.

Verifique operações de longa duração

Os métodos da API API Keys usam operações de longa duração. Se usar a API REST para criar e gerir chaves da API, é devolvido um objeto de operação a partir do pedido do método inicial. Usa o nome da operação para sondar a operação de longa duração. Quando o pedido de longa duração é concluído, a sondagem da operação devolve os dados do pedido de longa duração.

Para sondar uma operação da API API Keys de longa duração, use o método operations.get.

Substitua OPERATION_NAME pelo nome da operação devolvido pela operação de longa duração. Por exemplo, 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"

Limites nas chaves da API

Pode criar até 300 chaves da API por projeto. Este limite é um limite do sistema e não pode ser alterado através de um pedido de aumento da quota. Se precisar de mais chaves da API, tem de usar mais do que um projeto.

Pode adicionar até 1200 restrições de aplicações a uma chave da API.

O que se segue?