Répertorier les clés HMAC

Répertoriez les clés HMAC d'un projet.

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) {
  int count = 0;
  gcs::ListHmacKeysReader hmac_keys_list = client.ListHmacKeys();
  for (auto& key : hmac_keys_list) {
    if (!key) throw std::move(key).status();

    std::cout << "service_account_email = " << key->service_account_email()
              << "\naccess_id = " << key->access_id() << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No HMAC keys in default project\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;
using System.Collections.Generic;

public class ListHmacKeysSample
{
    public IEnumerable<HmacKeyMetadata> ListHmacKeys(string projectId = "your-project-id")
    {
        var storage = StorageClient.Create();
        var keys = storage.ListHmacKeys(projectId);

        foreach (var key in keys)
        {
            Console.WriteLine($"Service Account Email: {key.ServiceAccountEmail}");
            Console.WriteLine($"Access ID: {key.AccessId}");
        }
        return keys;
    }
}

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"
	"google.golang.org/api/iterator"
)

// listHMACKeys lists all HMAC keys associated with the project.
func listHMACKeys(w io.Writer, 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()
	iter := client.ListHMACKeys(ctx, projectID)
	var keys []*storage.HMACKey
	for {
		key, err := iter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, fmt.Errorf("ListHMACKeys: %w", err)
		}
		fmt.Fprintf(w, "Service Account Email: %s\n", key.ServiceAccountEmail)
		fmt.Fprintf(w, "Access ID: %s\n", key.AccessID)

		keys = append(keys, key)
	}

	return keys, 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.api.gax.paging.Page;
import com.google.cloud.storage.HmacKey;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

public class ListHmacKeys {
  public static void listHmacKeys(String projectId) throws StorageException {
    // The ID of the project to which the service account belongs.
    // String projectId = "project-id";

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

    Page<HmacKey.HmacKeyMetadata> page =
        storage.listHmacKeys(Storage.ListHmacKeysOption.projectId(projectId));

    for (HmacKey.HmacKeyMetadata metadata : page.iterateAll()) {
      System.out.println("Service Account Email: " + metadata.getServiceAccount().getEmail());
      System.out.println("Access ID: " + metadata.getAccessId());
    }
  }
}

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 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();

// List HMAC SA Keys' Metadata
async function listHmacKeys() {
  const [hmacKeys] = await storage.getHmacKeys({projectId});

  // hmacKeys is an array of HmacKey objects.
  for (const hmacKey of hmacKeys) {
    console.log(
      `Service Account Email: ${hmacKey.metadata.serviceAccountEmail}`
    );
    console.log(`Access Id: ${hmacKey.metadata.accessId}`);
  }
}

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;

/**
 * List HMAC keys.
 *
 * @param string $projectId The ID of your Google Cloud Platform project.
 *        (e.g. 'my-project-id')
 */
function list_hmac_keys(string $projectId): void
{
    $storage = new StorageClient();
    // By default hmacKeys will use the projectId used by StorageClient() to list HMAC Keys.
    $hmacKeys = $storage->hmacKeys(['projectId' => $projectId]);

    printf('HMAC Key\'s:' . PHP_EOL);
    foreach ($hmacKeys as $hmacKey) {
        printf('Service Account Email: %s' . PHP_EOL, $hmacKey->info()['serviceAccountEmail']);
        printf('Access Id: %s' . PHP_EOL, $hmacKey->info()['accessId']);
    }
}

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 list_keys(project_id):
    """
    List all HMAC keys associated with the project.
    """
    # project_id = "Your Google Cloud project ID"

    storage_client = storage.Client(project=project_id)
    hmac_keys = storage_client.list_hmac_keys(project_id=project_id)
    print("HMAC Keys:")
    for hmac_key in hmac_keys:
        print(
            f"Service Account Email: {hmac_key.service_account_email}"
        )
        print(f"Access ID: {hmac_key.access_id}")
    return hmac_keys

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 list_hmac_keys
  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new

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

  puts "HMAC Keys:"
  hmac_keys.all do |hmac_key|
    puts "Service Account Email: #{hmac_key.service_account_email}"
    puts "Access ID: #{hmac_key.access_id}"
  end
end

Étapes suivantes

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