Configura la autenticación del repositorio remoto en Maven Central

En este documento, se describe cómo configurar la autenticación en Maven Central. para los repositorios remotos de Artifact Registry.

En este documento, se supone que ya creaste una instancia de Maven de Artifact Registry repositorio remoto y una instancia de Maven Central. de servicio predeterminada.

Para obtener más información sobre repositorios remotos, consulta el Descripción general de los repositorios remotos.

Roles obligatorios

Para obtener los permisos que necesitas a fin de configurar la autenticación en Maven Central para repositorios remotos, solicita a tu administrador que te otorgue el los siguientes roles de IAM en el proyecto:

Si quieres obtener más información para otorgar roles, consulta Administra el acceso.

También puedes obtener los permisos necesarios mediante roles personalizados o cualquier otro rol predefinido.

Crea un token de acceso personal de Maven Central

  1. Accede a Maven Central.
  2. Crea un access-token.

    Usa el código de usuario para tu token de acceso personal como tu nombre de usuario cuando agregar tus credenciales a Artifact Registry. Para obtener más información administración de tokens de usuario en Maven Central, consulta Configuración de seguridad con tokens de usuario.

Guarda tu token de acceso personal en una versión del Secret

  1. Crea un secreto en Secret Manager.
  2. Guarda tu token de acceso personal de Maven Central como un versión del secreto.

Otorga a la cuenta de servicio de Artifact Registry acceso a tu secreto.

El agente de servicio de Artifact Registry actúa en nombre de Artifact Registry cuando interactúa con los servicios de Google Cloud. Para permitir que el agente de servicio use Secrets de Cloud Storage en Secret Manager, debes otorgarle al agente de servicio para ver tu versión del Secret.

El identificador del agente de servicio es el siguiente:

service-PROJECT-NUMBER@gcp-sa-artifactregistry.iam.gserviceaccount.com

PROJECT-NUMBER es el número de proyecto del proyecto de Google Cloud en el que se ejecuta Artifact Registry.

Para otorgar al agente de servicio de Artifact Registry el Acceso a secretos de Secret Manager rol:

Console

  1. Ve a la página Secret Manager en la consola de Google Cloud.

    Ir a la página Secret Manager

  2. En la página Secret Manager, haz clic en la casilla de verificación junto al nombre del secreto.

  3. Si aún no está abierto, haz clic en Mostrar panel de información para abrir el panel.

  4. En el panel de información, haz clic en Agregar principal.

  5. En el área de texto Principales nuevas, ingresa las direcciones de correo electrónico de los miembros que quieres agregar.

  6. En el menú desplegable Selecciona una función, selecciona Secret Manager y, luego, Administrador y descriptor de acceso a Secretos.

gcloud

$ gcloud secrets add-iam-policy-binding secret-id \
    --member="member" \
    --role="roles/secretmanager.secretAccessor"

En el ejemplo anterior, member es un miembro de IAM, como un usuario, un grupo o una cuenta de servicio.

C#

Para autenticarte en Artifact Registry, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


using Google.Cloud.SecretManager.V1;
using Google.Cloud.Iam.V1;

public class IamGrantAccessSample
{
    public Policy IamGrantAccess(
      string projectId = "my-project", string secretId = "my-secret",
      string member = "user:foo@example.com")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretName secretName = new SecretName(projectId, secretId);

        // Get current policy.
        Policy policy = client.GetIamPolicy(new GetIamPolicyRequest
        {
            ResourceAsResourceName = secretName,
        });

        // Add the user to the list of bindings.
        policy.AddRoleMember("roles/secretmanager.secretAccessor", member);

        // Save the updated policy.
        policy = client.SetIamPolicy(new SetIamPolicyRequest
        {
            ResourceAsResourceName = secretName,
            Policy = policy,
        });
        return policy;
    }
}

Go

Para autenticarte en Artifact Registry, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
)

// iamGrantAccess grants the given member access to the secret.
func iamGrantAccess(w io.Writer, name, member string) error {
	// name := "projects/my-project/secrets/my-secret"
	// member := "user:foo@example.com"

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %w", err)
	}
	defer client.Close()

	// Get the current IAM policy.
	handle := client.IAM(name)
	policy, err := handle.Policy(ctx)
	if err != nil {
		return fmt.Errorf("failed to get policy: %w", err)
	}

	// Grant the member access permissions.
	policy.Add(member, "roles/secretmanager.secretAccessor")
	if err = handle.SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("failed to save policy: %w", err)
	}

	fmt.Fprintf(w, "Updated IAM policy for %s\n", name)
	return nil
}

Java

Para autenticarte en Artifact Registry, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretName;
import com.google.iam.v1.Binding;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import java.io.IOException;

public class IamGrantAccess {

  public static void iamGrantAccess() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String secretId = "your-secret-id";
    String member = "user:foo@example.com";
    iamGrantAccess(projectId, secretId, member);
  }

  // Grant a member access to a particular secret.
  public static void iamGrantAccess(String projectId, String secretId, String member)
      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 "close" method on the client to safely clean up any remaining background resources.
    try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
      // Build the name from the version.
      SecretName secretName = SecretName.of(projectId, secretId);

      // Request the current IAM policy.
      Policy currentPolicy =
          client.getIamPolicy(
              GetIamPolicyRequest.newBuilder().setResource(secretName.toString()).build());

      // Build the new binding.
      Binding binding =
          Binding.newBuilder()
              .setRole("roles/secretmanager.secretAccessor")
              .addMembers(member)
              .build();

      // Create a new IAM policy from the current policy, adding the binding.
      Policy newPolicy = Policy.newBuilder().mergeFrom(currentPolicy).addBindings(binding).build();

      // Save the updated IAM policy.
      client.setIamPolicy(
          SetIamPolicyRequest.newBuilder()
              .setResource(secretName.toString())
              .setPolicy(newPolicy)
              .build());

      System.out.printf("Updated IAM policy for %s\n", secretId);
    }
  }
}

Node.js

Para autenticarte en Artifact Registry, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const name = 'projects/my-project/secrets/my-secret';
// const member = 'user:you@example.com';
//
// NOTE: Each member must be prefixed with its type. See the IAM documentation
// for more information: https://cloud.google.com/iam/docs/overview.

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

async function grantAccess() {
  // Get the current IAM policy.
  const [policy] = await client.getIamPolicy({
    resource: name,
  });

  // Add the user with accessor permissions to the bindings list.
  policy.bindings.push({
    role: 'roles/secretmanager.secretAccessor',
    members: [member],
  });

  // Save the updated IAM policy.
  await client.setIamPolicy({
    resource: name,
    policy: policy,
  });

  console.log(`Updated IAM policy for ${name}`);
}

grantAccess();

PHP

Para autenticarte en Artifact Registry, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient;

// Import the Secret Manager IAM library.
use Google\Cloud\Iam\V1\Binding;
use Google\Cloud\Iam\V1\GetIamPolicyRequest;
use Google\Cloud\Iam\V1\SetIamPolicyRequest;

/**
 * @param string $projectId Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $secretId  Your secret ID (e.g. 'my-secret')
 * @param string $member Your member (e.g. 'user:foo@example.com')
 */
function iam_grant_access(string $projectId, string $secretId, string $member): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

    // Build the resource name of the secret.
    $name = $client->secretName($projectId, $secretId);

    // Get the current IAM policy.
    $policy = $client->getIamPolicy((new GetIamPolicyRequest)->setResource($name));

    // Update the bindings to include the new member.
    $bindings = $policy->getBindings();
    $bindings[] = new Binding([
        'members' => [$member],
        'role' => 'roles/secretmanager.secretAccessor',
    ]);
    $policy->setBindings($bindings);

    // Build the request.
    $request = (new SetIamPolicyRequest)
        ->setResource($name)
        ->setPolicy($policy);

    // Save the updated policy to the server.
    $client->setIamPolicy($request);

    // Print out a success message.
    printf('Updated IAM policy for %s', $secretId);
}

Python

Para autenticarte en Artifact Registry, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

def iam_grant_access(
    project_id: str, secret_id: str, member: str
) -> iam_policy_pb2.SetIamPolicyRequest:
    """
    Grant the given member access to a secret.
    """

    # Import the Secret Manager client library.
    from google.cloud import secretmanager

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the secret.
    name = client.secret_path(project_id, secret_id)

    # Get the current IAM policy.
    policy = client.get_iam_policy(request={"resource": name})

    # Add the given member with access permissions.
    policy.bindings.add(role="roles/secretmanager.secretAccessor", members=[member])

    # Update the IAM Policy.
    new_policy = client.set_iam_policy(request={"resource": name, "policy": policy})

    # Print data about the secret.
    print(f"Updated IAM policy on {secret_id}")

Ruby

Para autenticarte en Artifact Registry, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

# project_id = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
# secret_id  = "YOUR-SECRET-ID"             # (e.g. "my-secret")
# member     = "USER-OR-ACCOUNT"            # (e.g. "user:foo@example.com")

# Require the Secret Manager client library.
require "google/cloud/secret_manager"

# Create a Secret Manager client.
client = Google::Cloud::SecretManager.secret_manager_service

# Build the resource name of the secret.
name = client.secret_path project: project_id, secret: secret_id

# Get the current IAM policy.
policy = client.get_iam_policy resource: name

# Add new member to current bindings
policy.bindings << Google::Iam::V1::Binding.new(
  members: [member],
  role:    "roles/secretmanager.secretAccessor"
)

# Update IAM policy
new_policy = client.set_iam_policy resource: name, policy: policy

# Print a success message.
puts "Updated IAM policy for #{secret_id}"

API

Nota: A diferencia de los otros ejemplos, esto reemplaza la política de IAM completa.

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets/secret-id:setIamPolicy" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --data "{\"policy\": {\"bindings\": [{\"members\": [\"member\"], \"role\": \"roles/secretmanager.secretAccessor\"}]}}"

Para obtener más información sobre cómo otorgar o revocar el acceso a los Secrets, consulta Administra el acceso a los secretos.

Agrega credenciales de Maven Central a tu repositorio remoto

Para actualizar tu repositorio remoto con tus credenciales de Maven Central, sigue estos pasos:

Console

  1. Abre la página Repositorios en la consola de Google Cloud.

    Abrir la página Repositorios

  2. En la lista de repositorios, selecciona el repositorio y haz clic Edita el repositorio.

  3. En la sección Modo de autenticación de repositorio remoto, actualiza o agrega tu código de usuario de Maven Central asociado con tu token de acceso personal como tu nombre de usuario y la versión del Secret que contiene token de acceso.

gcloud CLI

Para actualizar tu repositorio remoto con tus credenciales de Maven Central, ejecuta el comando siguiente comando:

gcloud artifacts repositories update REPOSITORY \
    --project=PROJECT_ID \
    --location=LOCATION \
    --remote-username=USER_CODE \
    --remote-password-secret-version=projects/SECRET_PROJECT_ID/secrets/SECRET_ID/versions/SECRET_VERSION

Reemplaza lo siguiente:

  • REPOSITORY por el nombre del recurso remoto de Artifact Registry en un repositorio de confianza.
  • PROJECT_ID por el ID del proyecto de Google Cloud
  • LOCATION por la configuración regional o multirregional location para el repositorio. Puedes omitir esta marca si estableces un valor predeterminado. Cómo ver una lista de ubicaciones compatibles, ejecuta el comando gcloud artifacts locations list.
  • USER_CODE: Es el código de usuario asociado con tu cuenta de Maven. Token de acceso central. Para obtener más información sobre la administración de tokens de usuario en Maven Para obtener información central, consulta Configuración de seguridad con tokens de usuario.
  • SECRET_PROJECT_ID por el ID del proyecto en la que creaste el Secret.
  • SECRET_ID por el nombre que le asignaste a tu secreto.
  • SECRET_VERSION por la versión del secreto que guardaste tu token de acceso de Maven Central. s

Tus credenciales se usarán la próxima vez que el repositorio remoto envíe una solicitud para un artefacto de la fuente upstream.