Désactiver la clé HMAC d'un compte de service

Permet de passer la clé HMAC d'un compte de service à l'état "Inactif".

En savoir plus

Pour obtenir une documentation détaillée incluant cet exemple de code, consultez la page suivante :

Exemple de code

C++

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage C++.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& access_id) {
  StatusOr<gcs::HmacKeyMetadata> updated = client.UpdateHmacKey(
      access_id, gcs::HmacKeyMetadata().set_state(
                     gcs::HmacKeyMetadata::state_inactive()));
  if (!updated) throw std::move(updated).status();

  if (updated->state() != gcs::HmacKeyMetadata::state_inactive()) {
    throw std::runtime_error("The HMAC key is active, this is unexpected");
  }
  std::cout << "The HMAC key is now inactive\nFull metadata: " << *updated
            << "\n";
}

C#

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage C#.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class DeactivateHmacKeySample
{
    public HmacKeyMetadata DeactivateHmacKey(
        string projectId = "your-project-id",
        string accessId = "your-access-id")
    {
        var storage = StorageClient.Create();
        var metadata = storage.GetHmacKey(projectId, accessId);
        metadata.State = HmacKeyStates.Inactive;
        var updatedMetadata = storage.UpdateHmacKey(metadata);

        Console.WriteLine("The HMAC key is now inactive.");
        Console.WriteLine("The HMAC key metadata is:");
        Console.WriteLine($"ID: {updatedMetadata.Id}");
        Console.WriteLine($"Access ID: {updatedMetadata.AccessId}");
        Console.WriteLine($"Project ID: {updatedMetadata.ProjectId}");
        Console.WriteLine($"Service Account Email: {updatedMetadata.ServiceAccountEmail}");
        Console.WriteLine($"State: {updatedMetadata.State}");
        Console.WriteLine($"Time Created: {updatedMetadata.TimeCreated}");
        Console.WriteLine($"Time Updated: {updatedMetadata.Updated}");
        Console.WriteLine($"ETag: {updatedMetadata.ETag}");
        return updatedMetadata;
    }
}

Go

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Go.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// deactivateHMACKey deactivates the HMAC key with the given access ID.
func deactivateHMACKey(w io.Writer, accessID string, projectID string) (*storage.HMACKey, error) {
	ctx := context.Background()

	// Initialize client.
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()
	handle := client.HMACKeyHandle(projectID, accessID)
	key, err := handle.Update(ctx, storage.HMACKeyAttrsToUpdate{State: "INACTIVE"})
	if err != nil {
		return nil, fmt.Errorf("Update: %w", err)
	}

	fmt.Fprintln(w, "The HMAC key metadata is:")
	fmt.Fprintf(w, "%+v", key)

	return key, nil
}

Java

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Java.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


import com.google.cloud.storage.HmacKey;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
import java.util.Date;

public class DeactivateHmacKey {
  public static void deactivateHmacKey(String accessId, String projectId) throws StorageException {
    // The access ID of the HMAC key.
    // String accessId = "GOOG0234230X00";

    // The ID of the project to which the service account belongs.
    // String projectId = "project-id";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    HmacKey.HmacKeyMetadata metadata =
        storage.getHmacKey(accessId, Storage.GetHmacKeyOption.projectId(projectId));
    HmacKey.HmacKeyMetadata newMetadata =
        storage.updateHmacKeyState(metadata, HmacKey.HmacKeyState.INACTIVE);

    System.out.println("The HMAC key is now inactive.");
    System.out.println("The HMAC key metadata is:");
    System.out.println("ID: " + newMetadata.getId());
    System.out.println("Access ID: " + newMetadata.getAccessId());
    System.out.println("Project ID: " + newMetadata.getProjectId());
    System.out.println("Service Account Email: " + newMetadata.getServiceAccount().getEmail());
    System.out.println("State: " + newMetadata.getState().toString());
    System.out.println("Time Created: " + new Date(newMetadata.getCreateTime()).toString());
    System.out.println("Time Updated: " + new Date(newMetadata.getUpdateTime()).toString());
    System.out.println("ETag: " + newMetadata.getEtag());
  }
}

Node.js

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Node.js.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The access ID of the HMAC key
// const hmacKeyAccessId = 'GOOG0234230X00';

// The ID of the project to which the service account belongs
// const projectId = 'project-id';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

// Deactivate HMAC SA Key
async function deactivateHmacKey() {
  const hmacKey = storage.hmacKey(hmacKeyAccessId, {projectId});
  const [hmacKeyMetadata] = await hmacKey.setMetadata({state: 'INACTIVE'});

  console.log('The HMAC key is now inactive.');
  console.log('The HMAC key metadata is:');
  for (const [key, value] of Object.entries(hmacKeyMetadata)) {
    console.log(`${key}: ${value}`);
  }
}

PHP

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage PHP.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

use Google\Cloud\Storage\StorageClient;

/**
 * Deactivate an HMAC key.
 *
 * @param string $projectId The ID of your Google Cloud Platform project.
 *        (e.g. 'my-project-id')
 * @param string $accessId Access ID for an inactive HMAC key.
 *        (e.g. 'GOOG0234230X00')
 */
function deactivate_hmac_key(string $projectId, string $accessId): void
{
    $storage = new StorageClient();
    // By default hmacKey will use the projectId used by StorageClient().
    $hmacKey = $storage->hmacKey($accessId, $projectId);

    $hmacKey->update('INACTIVE');

    print('The HMAC key is now inactive.' . PHP_EOL);
    printf('HMAC key Metadata: %s' . PHP_EOL, print_r($hmacKey->info(), true));
}

Python

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Python.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

from google.cloud import storage

def deactivate_key(access_id, project_id):
    """
    Deactivate the HMAC key with the given access ID.
    """
    # project_id = "Your Google Cloud project ID"
    # access_id = "ID of an active HMAC key"

    storage_client = storage.Client(project=project_id)

    hmac_key = storage_client.get_hmac_key_metadata(
        access_id, project_id=project_id
    )
    hmac_key.state = "INACTIVE"
    hmac_key.update()

    print("The HMAC key is now inactive.")
    print("The HMAC key metadata is:")
    print(f"Service Account Email: {hmac_key.service_account_email}")
    print(f"Key ID: {hmac_key.id}")
    print(f"Access ID: {hmac_key.access_id}")
    print(f"Project ID: {hmac_key.project}")
    print(f"State: {hmac_key.state}")
    print(f"Created At: {hmac_key.time_created}")
    print(f"Updated At: {hmac_key.updated}")
    print(f"Etag: {hmac_key.etag}")
    return hmac_key

Ruby

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Ruby.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

def deactivate_hmac_key access_id:
  # The access ID of the HMAC key
  # access_id = "GOOG0234230X00"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new

  # By default Storage#hmac_keys uses the Storage client project_id
  hmac_key = storage.hmac_key access_id

  hmac_key.inactive!

  puts "The HMAC key is now inactive."
  puts "The HMAC key metadata is:"
  puts "Key ID:                #{hmac_key.id}"
  puts "Service Account Email: #{hmac_key.service_account_email}"
  puts "Access ID:             #{hmac_key.access_id}"
  puts "Project ID:            #{hmac_key.project_id}"
  puts "Active:                #{hmac_key.active?}"
  puts "Created At:            #{hmac_key.created_at}"
  puts "Updated At:            #{hmac_key.updated_at}"
  puts "Etag:                  #{hmac_key.etag}"
end

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'explorateur d'exemples Google Cloud.