Mencantumkan kunci HMAC

Mencantumkan kunci HMAC dalam project.

Mempelajari lebih lanjut

Untuk dokumentasi mendetail yang menyertakan contoh kode ini, lihat referensi berikut:

Contoh kode

C++

Untuk informasi selengkapnya, lihat Dokumentasi referensi Cloud Storage C++ API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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#

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C# API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Go API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Java API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Node.js API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * 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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage PHP API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Python API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Ruby API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Langkah selanjutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contoh Google Cloud.