Autenticar para usar bibliotecas de cliente

En esta página se describe cómo puedes usar bibliotecas de cliente para acceder a las APIs de Google.

Las bibliotecas de cliente facilitan el acceso a las Google Cloud APIs con un lenguaje compatible. Puedes usar las APIs de Google Cloud directamente haciendo solicitudes sin formato al servidor, pero las bibliotecas de cliente ofrecen simplificaciones que reducen significativamente la cantidad de código que tienes que escribir. Esto es especialmente cierto en el caso de la autenticación, ya que las bibliotecas de cliente admiten las credenciales predeterminadas de la aplicación (ADC).

Si aceptas configuraciones de credenciales (JSON, archivos o flujos) de una fuente externa (por ejemplo, un cliente), consulta los requisitos de seguridad al usar configuraciones de credenciales de una fuente externa.

Usar credenciales de aplicación predeterminadas con bibliotecas de cliente

Para usar las credenciales de aplicación predeterminadas y autenticar tu aplicación, primero debes configurar las ADC en el entorno en el que se ejecuta tu aplicación. Cuando usas la biblioteca de cliente para crear un cliente, la biblioteca de cliente comprueba automáticamente las credenciales que has proporcionado a ADC y las usa para autenticarse en las APIs que usa tu código. Tu aplicación no necesita autenticarse explícitamente ni gestionar tokens. Las bibliotecas de autenticación se encargan de estos requisitos automáticamente.

En un entorno de desarrollo local, puedes configurar ADC con tus credenciales de usuario o con la suplantación de identidad de una cuenta de servicio mediante la CLI de gcloud. En los entornos de producción, la ADC se configura asociando una cuenta de servicio.

Ejemplo de creación de un cliente

En los siguientes ejemplos de código se crea un cliente para el servicio Cloud Storage. Es probable que tu código necesite diferentes clientes. Estos ejemplos solo tienen como objetivo mostrar cómo puedes crear un cliente y usarlo sin ningún código para autenticarte explícitamente.

Antes de ejecutar los siguientes ejemplos, debes completar estos pasos:

Go

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

Usar claves de API con bibliotecas de cliente

Solo puedes usar claves de API con bibliotecas de cliente de APIs que acepten claves de API. Además, la clave de API no debe tener una restricción de API que impida que se use en la API.

Para obtener más información sobre las claves de API creadas en el modo Exprés, consulta las preguntas frecuentes sobre el modo Exprés de Google Cloud.

En este ejemplo se usa la API Cloud Natural Language, que acepta claves de API, para mostrar cómo se proporciona una clave de API a la biblioteca.

C#

Para ejecutar este ejemplo, debes instalar la biblioteca de cliente de Natural Language.


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 ejecutar este ejemplo, debes instalar la biblioteca de cliente de Natural Language.

#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";
}

Go

Para ejecutar este ejemplo, debes instalar la biblioteca de cliente de Natural Language.

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 ejecutar este ejemplo, debes instalar la biblioteca de cliente de Natural Language.


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 ejecutar este ejemplo, debes instalar la biblioteca de cliente de Natural Language.


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 ejecutar este ejemplo, debes instalar la biblioteca de cliente de Natural Language.

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

Cuando uses claves de API en tus aplicaciones, asegúrate de que se mantengan protegidas tanto durante el almacenamiento como durante la transmisión. Si expones públicamente tus claves de API, es posible que se apliquen cargos inesperados a tu cuenta. Para obtener más información, consulta las prácticas recomendadas para gestionar las claves de API.

Requisitos de seguridad al usar configuraciones de credenciales de una fuente externa

Normalmente, las configuraciones de credenciales se generan mediante comandos de la CLI de gcloud o con la Google Cloud consola. Por ejemplo, puedes usar la CLI de gcloud para generar un archivo ADC local o un archivo de configuración de inicio de sesión. Del mismo modo, puedes usar la consola de Google Cloud para crear y descargar una clave de cuenta de servicio.

Sin embargo, en algunos casos de uso, una entidad externa te proporciona configuraciones de credenciales. Estas configuraciones se deben usar para autenticarte en las APIs de Google.

Algunos tipos de configuraciones de credenciales incluyen endpoints y rutas de archivos, que las bibliotecas de autenticación usan para adquirir un token. Cuando aceptes configuraciones de credenciales de una fuente externa, debes validar la configuración antes de usarla. Si no valida la configuración, un agente malintencionado podría usar la credencial para poner en peligro sus sistemas y datos.

Validar las configuraciones de credenciales de fuentes externas

La forma en que debes validar tus credenciales externas depende de los tipos de credenciales que acepte tu aplicación.

Validar claves de cuenta de servicio

Si tu aplicación solo acepta claves de cuenta de servicio, usa un cargador de credenciales específico para claves de cuenta de servicio, como se muestra en los siguientes ejemplos. El cargador de credenciales específico del tipo solo analiza los campos presentes en las claves de cuentas de servicio, que no exponen ninguna vulnerabilidad.

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)

Si no puedes usar un cargador de credenciales específico de un tipo, valida la credencial confirmando que el valor del campo type es service_account. Si el valor del campo type es otro, no uses la clave de la cuenta de servicio.

Validar otras configuraciones de credenciales

Si tu aplicación acepta cualquier tipo de credencial además de una clave de cuenta de servicio, debes realizar una verificación adicional. Entre los ejemplos de otros tipos de configuraciones de credenciales se incluyen los archivos de credenciales de ADC, los archivos de credenciales de federación de identidades de cargas de trabajo o los archivos de configuración de inicio de sesión de federación de identidades de Workforce.

En la siguiente tabla se indican los campos que debe validar, si están presentes en sus credenciales. No todos estos campos están presentes en todas las configuraciones de credenciales.

Campo Finalidad Valor previsto
service_account_impersonation_url Las bibliotecas de autenticación usan este campo para acceder a un endpoint y generar un token de acceso para la cuenta de servicio cuya identidad se está suplantando. https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/service account email:generateAccessToken
token_url Las bibliotecas de autenticación envían un token externo a este endpoint para intercambiarlo por un token de acceso federado. https://sts.googleapis.com/v1/token
credential_source.file Las bibliotecas de autenticación leen un token externo del archivo ubicado en la ubicación especificada en este campo y lo envían al endpoint de token_url. Ruta de un archivo que contiene un token externo. Deberías reconocer esta ruta.
credential_source.url Un endpoint que devuelve un token externo. Las bibliotecas de autenticación envían una solicitud a esta URL y envían la respuesta al endpoint token_url.

Uno de los siguientes elementos:

  • Un endpoint conocido proporcionado por tu proveedor de servicios en la nube.
  • Un endpoint que has configurado explícitamente para proporcionar tokens.
credential_source.executable.command Si la variable de entorno GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES tiene el valor 1, las bibliotecas de autenticación ejecutan este comando o archivo ejecutable. Un archivo ejecutable o un comando que devuelve un token externo. Deberías reconocer este comando y validar que es seguro.
credential_source.aws.url Las bibliotecas de autenticación envían una solicitud a esta URL para obtener un token de seguridad de AWS.

Cualquiera de estos valores exactos:

  • 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 Las bibliotecas de autenticación envían una solicitud a esta URL para obtener la región de AWS activa.

Cualquiera de estos valores exactos:

  • 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 Las bibliotecas de autenticación envían una solicitud a esta URL para obtener el token de sesión de AWS.

Cualquiera de estos valores exactos:

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

Siguientes pasos