Autentique-se para usar bibliotecas de cliente

Esta página descreve como pode usar bibliotecas cliente para aceder às APIs Google.

As bibliotecas cliente facilitam o acesso às Google Cloud APIs através de uma linguagem suportada. Pode usar as Google Cloud APIs diretamente fazendo pedidos não processados ao servidor, mas as bibliotecas cliente oferecem simplificações que reduzem significativamente a quantidade de código que tem de escrever. Isto é especialmente verdade para a autenticação, uma vez que as bibliotecas cliente suportam as Credenciais padrão da aplicação (ADC).

Se aceitar configurações de credenciais (JSON, ficheiros ou streams) de uma fonte externa (por exemplo, um cliente), reveja os requisitos de segurança quando usar configurações de credenciais de uma fonte externa.

Use as Credenciais padrão da aplicação com bibliotecas de cliente

Para usar as credenciais padrão da aplicação para autenticar a sua aplicação, tem de configurar as ADC para o ambiente onde a sua aplicação está a ser executada. Quando usa a biblioteca cliente para criar um cliente, a biblioteca cliente verifica automaticamente e usa as credenciais que forneceu ao ADC para fazer a autenticação nas APIs que o seu código usa. A sua aplicação não precisa de autenticar explicitamente nem gerir tokens. Estes requisitos são geridos automaticamente pelas bibliotecas de autenticação.

Para um ambiente de desenvolvimento local, pode configurar o ADC com as suas credenciais de utilizador ou com a representação da conta de serviço através da CLI gcloud. Para ambientes de produção, configure o ADC associando uma conta de serviço.

Exemplo de criação de cliente

Os seguintes exemplos de código criam um cliente para o serviço Cloud Storage. É provável que o seu código precise de clientes diferentes. Estes exemplos destinam-se apenas a mostrar como pode criar um cliente e usá-lo sem código para autenticar explicitamente.

Antes de poder executar os seguintes exemplos, tem de concluir os seguintes passos:

Ir

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/storage"
	"google.golang.org/api/iterator"
)

// authenticateImplicitWithAdc uses Application Default Credentials
// to automatically find credentials and authenticate.
func authenticateImplicitWithAdc(w io.Writer, projectId string) error {
	// projectId := "your_project_id"

	ctx := context.Background()

	// NOTE: Replace the client created below with the client required for your application.
	// Note that the credentials are not specified when constructing the client.
	// The client library finds your credentials using ADC.
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	it := client.Buckets(ctx, projectId)
	for {
		bucketAttrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "Bucket: %v\n", bucketAttrs.Name)
	}

	fmt.Fprintf(w, "Listed all storage buckets.\n")

	return nil
}

Java


import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.io.IOException;

public class AuthenticateImplicitWithAdc {

  public static void main(String[] args) throws IOException {
    // TODO(Developer):
    //  1. Before running this sample,
    //  set up Application Default Credentials as described in
    //  https://cloud.google.com/docs/authentication/external/set-up-adc
    //  2. Replace the project variable below.
    //  3. Make sure you have the necessary permission to list storage buckets
    //  "storage.buckets.list"
    String projectId = "your-google-cloud-project-id";
    authenticateImplicitWithAdc(projectId);
  }

  // When interacting with Google Cloud Client libraries, the library can auto-detect the
  // credentials to use.
  public static void authenticateImplicitWithAdc(String project) throws IOException {

    // *NOTE*: Replace the client created below with the client required for your application.
    // Note that the credentials are not specified when constructing the client.
    // Hence, the client library will look for credentials using ADC.
    //
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    Storage storage = StorageOptions.newBuilder().setProjectId(project).build().getService();

    System.out.println("Buckets:");
    Page<Bucket> buckets = storage.list();
    for (Bucket bucket : buckets.iterateAll()) {
      System.out.println(bucket.toString());
    }
    System.out.println("Listed all storage buckets.");
  }
}

Node.js

/**
 * TODO(developer):
 *  1. Uncomment and replace these variables before running the sample.
 *  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 list storage buckets "storage.buckets.list"
 *    (https://cloud.google.com/storage/docs/access-control/iam-permissions#bucket_permissions)
 */
// const projectId = 'YOUR_PROJECT_ID';

const {Storage} = require('@google-cloud/storage');

async function authenticateImplicitWithAdc() {
  // This snippet demonstrates how to list buckets.
  // NOTE: Replace the client created below with the client required for your application.
  // Note that the credentials are not specified when constructing the client.
  // The client library finds your credentials using ADC.
  const storage = new Storage({
    projectId,
  });
  const [buckets] = await storage.getBuckets();
  console.log('Buckets:');

  for (const bucket of buckets) {
    console.log(`- ${bucket.name}`);
  }

  console.log('Listed all storage buckets.');
}

authenticateImplicitWithAdc();

PHP

// Imports the Cloud Storage client library.
use Google\Cloud\Storage\StorageClient;

/**
 * Authenticate to a cloud client library using a service account implicitly.
 *
 * @param string $projectId The Google project ID.
 */
function auth_cloud_implicit($projectId)
{
    $config = [
        'projectId' => $projectId,
    ];

    # If you don't specify credentials when constructing the client, the
    # client library will look for credentials in the environment.
    $storage = new StorageClient($config);

    # Make an authenticated API request (listing storage buckets)
    foreach ($storage->buckets() as $bucket) {
        printf('Bucket: %s' . PHP_EOL, $bucket->name());
    }
}

Python


from google.cloud import storage


def authenticate_implicit_with_adc(project_id="your-google-cloud-project-id"):
    """
    When interacting with Google Cloud Client libraries, the library can auto-detect the
    credentials to use.

    // TODO(Developer):
    //  1. Before running this sample,
    //  set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    //  2. Replace the project variable.
    //  3. Make sure that the user account or service account that you are using
    //  has the required permissions. For this sample, you must have "storage.buckets.list".
    Args:
        project_id: The project id of your Google Cloud project.
    """

    # This snippet demonstrates how to list buckets.
    # *NOTE*: Replace the client created below with the client required for your application.
    # Note that the credentials are not specified when constructing the client.
    # Hence, the client library will look for credentials using ADC.
    storage_client = storage.Client(project=project_id)
    buckets = storage_client.list_buckets()
    print("Buckets:")
    for bucket in buckets:
        print(bucket.name)
    print("Listed all storage buckets.")

Ruby

def authenticate_implicit_with_adc project_id:
  # The ID of your Google Cloud project
  # project_id = "your-google-cloud-project-id"

  ###
  # When interacting with Google Cloud Client libraries, the library can auto-detect the
  # credentials to use.
  # TODO(Developer):
  #   1. Before running this sample,
  #      set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
  #   2. Replace the project variable.
  #   3. Make sure that the user account or service account that you are using
  #      has the required permissions. For this sample, you must have "storage.buckets.list".
  ###

  require "google/cloud/storage"

  # This sample demonstrates how to list buckets.
  # *NOTE*: Replace the client created below with the client required for your application.
  # Note that the credentials are not specified when constructing the client.
  # Hence, the client library will look for credentials using ADC.
  storage = Google::Cloud::Storage.new project_id: project_id
  buckets = storage.buckets
  puts "Buckets: "
  buckets.each do |bucket|
    puts bucket.name
  end
  puts "Plaintext: Listed all storage buckets."
end

Use chaves da API com bibliotecas cliente

Pode usar chaves de API apenas com bibliotecas cliente para APIs que aceitem chaves de API. Além disso, a chave da API não pode ter uma restrição da API que impeça a sua utilização para a API.

Para mais informações sobre as chaves da API criadas no modo expresso, consulte as Perguntas frequentes sobre o modo expresso do Google Cloud.

Este exemplo usa a API Cloud Natural Language, que aceita chaves da API, para demonstrar como forneceria uma chave da API à biblioteca.

C#

Para executar este exemplo, tem de instalar a biblioteca cliente de linguagem natural.


using Google.Cloud.Language.V1;
using System;

public class UseApiKeySample
{
    public void AnalyzeSentiment(string apiKey)
    {
        LanguageServiceClient client = new LanguageServiceClientBuilder
        {
            ApiKey = apiKey
        }.Build();

        string text = "Hello, world!";

        AnalyzeSentimentResponse response = client.AnalyzeSentiment(Document.FromPlainText(text));
        Console.WriteLine($"Text: {text}");
        Sentiment sentiment = response.DocumentSentiment;
        Console.WriteLine($"Sentiment: {sentiment.Score}, {sentiment.Magnitude}");
        Console.WriteLine("Successfully authenticated using the API key");
    }
}

C++

Para executar este exemplo, tem de instalar a biblioteca cliente de linguagem natural.

#include "google/cloud/language/v1/language_client.h"
#include "google/cloud/credentials.h"
#include "google/cloud/options.h"

void AuthenticateWithApiKey(std::vector<std::string> const& argv) {
  if (argv.size() != 2) {
    throw google::cloud::testing_util::Usage{
        "authenticate-with-api-key <project-id> <api-key>"};
  }
  namespace gc = ::google::cloud;
  auto options = gc::Options{}.set<gc::UnifiedCredentialsOption>(
      gc::MakeApiKeyCredentials(argv[1]));
  auto client = gc::language_v1::LanguageServiceClient(
      gc::language_v1::MakeLanguageServiceConnection(options));

  auto constexpr kText = "Hello, world!";

  google::cloud::language::v1::Document d;
  d.set_content(kText);
  d.set_type(google::cloud::language::v1::Document::PLAIN_TEXT);

  auto response = client.AnalyzeSentiment(d, {});
  if (!response) throw std::move(response.status());
  auto const& sentiment = response->document_sentiment();
  std::cout << "Text: " << kText << "\n";
  std::cout << "Sentiment: " << sentiment.score() << ", "
            << sentiment.magnitude() << "\n";
  std::cout << "Successfully authenticated using the API key\n";
}

Ir

Para executar este exemplo, tem de instalar a biblioteca cliente de linguagem natural.

import (
	"context"
	"fmt"
	"io"

	language "cloud.google.com/go/language/apiv1"
	"cloud.google.com/go/language/apiv1/languagepb"
	"google.golang.org/api/option"
)

// authenticateWithAPIKey authenticates with an API key for Google Language
// service.
func authenticateWithAPIKey(w io.Writer, apiKey string) error {
	// apiKey := "api-key-string"

	ctx := context.Background()

	// Initialize the Language Service client and set the API key.
	client, err := language.NewClient(ctx, option.WithAPIKey(apiKey))
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	text := "Hello, world!"
	// Make a request to analyze the sentiment of the text.
	res, err := client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_Content{
				Content: text,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
	})
	if err != nil {
		return fmt.Errorf("AnalyzeSentiment: %w", err)
	}

	fmt.Fprintf(w, "Text: %s\n", text)
	fmt.Fprintf(w, "Sentiment score: %v\n", res.DocumentSentiment.Score)
	fmt.Fprintln(w, "Successfully authenticated using the API key.")

	return nil
}

Node.js

Para executar este exemplo, tem de instalar a biblioteca cliente de linguagem natural.


const {
  v1: {LanguageServiceClient},
} = require('@google-cloud/language');

/**
 * Authenticates with an API key for Google Language service.
 *
 * @param {string} apiKey An API Key to use
 */
async function authenticateWithAPIKey(apiKey) {
  const language = new LanguageServiceClient({apiKey});

  // Alternatively:
  // const {GoogleAuth} = require('google-auth-library');
  // const auth = new GoogleAuth({apiKey});
  // const language = new LanguageServiceClient({auth});

  const text = 'Hello, world!';

  const [response] = await language.analyzeSentiment({
    document: {
      content: text,
      type: 'PLAIN_TEXT',
    },
  });

  console.log(`Text: ${text}`);
  console.log(
    `Sentiment: ${response.documentSentiment.score}, ${response.documentSentiment.magnitude}`,
  );
  console.log('Successfully authenticated using the API key');
}

authenticateWithAPIKey();

Python

Para executar este exemplo, tem de instalar a biblioteca cliente de linguagem natural.


from google.cloud import language_v1


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

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

    Args:
        api_key_string: The API key to authenticate to the service.
    """

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

    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")

Ruby

Para executar este exemplo, tem de instalar a biblioteca cliente de linguagem natural.

require "googleauth"
require "google/cloud/language/v1"

def authenticate_with_api_key api_key_string
  # Authenticates with an API key for Google Language service.
  #
  # TODO(Developer): Uncomment the following line and set the value before running this sample.
  #
  # api_key_string = "mykey12345"
  #
  # Note: You can also set the API key via environment variable:
  #   export GOOGLE_API_KEY=your-api-key
  # and use Google::Auth::APIKeyCredentials.from_env method to load it.
  # Example:
  #   credentials = Google::Auth::APIKeyCredentials.from_env
  #   if credentials.nil?
  #     puts "No API key found in environment"
  #     exit
  #   end

  # Initialize API key credentials using the class factory method
  credentials = Google::Auth::APIKeyCredentials.make_creds api_key: api_key_string

  # Initialize the Language Service client with the API key credentials
  client = Google::Cloud::Language::V1::LanguageService::Client.new do |config|
    config.credentials = credentials
  end

  # Create a document to analyze
  text = "Hello, world!"
  document = {
    content: text,
    type: :PLAIN_TEXT
  }

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

  puts "Text: #{text}"
  puts "Sentiment: #{sentiment.score}, #{sentiment.magnitude}"
  puts "Successfully authenticated using the API key"
end

Quando usar chaves de API nas suas aplicações, certifique-se de que as mantém seguras durante o armazenamento e a transmissão. A exposição pública das chaves da API pode resultar em cobranças inesperadas na sua conta. Para mais informações, consulte o artigo Práticas recomendadas para gerir chaves da API.

Requisitos de segurança ao usar configurações de credenciais de uma origem externa

Normalmente, gera configurações de credenciais através de comandos da CLI gcloud ou através da Google Cloud consola. Por exemplo, pode usar a CLI gcloud para gerar um ficheiro ADC local ou um ficheiro de configuração de início de sessão. Da mesma forma, pode usar a consola Google Cloud para criar e transferir uma chave de conta de serviço.

No entanto, para alguns exemplos de utilização, as configurações de credenciais são-lhe fornecidas por uma entidade externa. Estas configurações de credenciais destinam-se a ser usadas para autenticar nas APIs Google.

Alguns tipos de configurações de credenciais incluem pontos finais e caminhos de ficheiros, que as bibliotecas de autenticação usam para adquirir um token. Quando aceita configurações de credenciais de uma origem externa, tem de validar a configuração antes de a usar. Se não validar a configuração, um agente malicioso pode usar a credencial para comprometer os seus sistemas e dados.

Valide as configurações de credenciais de origens externas

A forma como tem de validar as suas credenciais externas depende dos tipos de credenciais que a sua aplicação aceita.

Valide as chaves de contas de serviço

Se a sua aplicação aceitar apenas chaves de contas de serviço, use um carregador de credenciais específico das chaves de contas de serviço, conforme mostrado nos exemplos seguintes. O carregador de credenciais específico do tipo analisa apenas os campos presentes para as chaves de conta de serviço, que não expõem vulnerabilidades.

C#

var saCredential = ServiceAccountCredential.FromServiceAccountData(stream);

C++

auto cred = google::cloud::MakeServiceAccountCredentials(json)

Java

ServiceAccountCredentials credentials =
      ServiceAccountCredentials.fromStream(credentialsStream);

Node.js

const keys = JSON.parse(json_input)
const authClient = JWT.fromJSON(keys);

PHP

cred = new Google\Auth\Credentials\ServiceAccountCredentials($scope, $jsonKey);

Python

cred = service_account.Credentials.from_service_account_info(json_data)

Ruby

creds = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: json_stream)

Se não puder usar um carregador de credenciais específico do tipo, valide a credencial confirmando que o valor do campo type é service_account. Se o valor do campo type for qualquer outro valor, não use a chave da conta de serviço.

Valide outras configurações de credenciais

Se a sua aplicação aceitar qualquer tipo de credencial além de uma chave de conta de serviço, tem de efetuar uma validação adicional. Exemplos de outros tipos de configurações de credenciais incluem ficheiros de credenciais da ADC, ficheiros de credenciais da federação de identidades da carga de trabalho ou ficheiros de configuração de início de sessão da federação de identidades da força de trabalho.

A tabela seguinte apresenta os campos que tem de validar, se estiverem presentes nas suas credenciais. Nem todos estes campos estão presentes em todas as configurações de credenciais.

Campo Finalidade Valor esperado
service_account_impersonation_url As bibliotecas de autenticação usam este campo para aceder a um ponto final para gerar um token de acesso para a conta de serviço cuja identidade está a ser roubada. https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/service account email:generateAccessToken
token_url As bibliotecas de autenticação enviam um token externo para este ponto final para o trocar por um token de acesso federado. https://sts.googleapis.com/v1/token
credential_source.file As bibliotecas de autenticação leem um token externo do ficheiro na localização especificada por este campo e enviam-no para o ponto final token_url. O caminho de um ficheiro que contém um token externo. Deve reconhecer este caminho.
credential_source.url Um ponto final que devolve um token externo. As bibliotecas de autenticação enviam um pedido para este URL e enviam a resposta para o ponto final token_url.

Um dos seguintes itens:

  • Um ponto final conhecido fornecido pelo seu fornecedor de nuvem.
  • Um ponto final que configurou explicitamente para fornecer tokens.
credential_source.executable.command Se a variável de ambiente GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES estiver definida como 1, as bibliotecas de autenticação executam este comando ou ficheiro executável. Um ficheiro executável ou um comando que devolve um token externo. Deve reconhecer este comando e validar que é seguro.
credential_source.aws.url As bibliotecas de autenticação enviam um pedido para este URL para obter um token de segurança da AWS.

Qualquer um destes valores exatos:

  • http://169.254.169.254/latest/meta-data/iam/security-credentials
  • http://[fd00:ec2::254]/latest/meta-data/iam/security-credentials
credential_source.aws.region_url As bibliotecas de autenticação enviam um pedido para este URL para obter a região da AWS ativa.

Qualquer um destes valores exatos:

  • http://169.254.169.254/latest/meta-data/placement/availability-zone
  • http://[fd00:ec2::254]/latest/meta-data/placement/availability-zone
credential_source.aws.imdsv2_session_token_url As bibliotecas de autenticação enviam um pedido para este URL para obter o token de sessão da AWS.

Qualquer um destes valores exatos:

  • http://169.254.169.254/latest/api/token
  • http://[fd00:ec2::254]/latest/api/token

O que se segue?