HMAC-Schlüssel aktivieren

Aktualisiert den Status eines HMAC-Schlüssels zu „Aktiv“.

Weitere Informationen

Eine ausführliche Dokumentation, die dieses Codebeispiel enthält, finden Sie hier:

Codebeispiel

C++

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage C++ API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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_active()));
  if (!updated) throw std::move(updated).status();

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

C#

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage C# API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

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

        Console.WriteLine("The HMAC key is now active.");
        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

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Go API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

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

// activateHMACKey activates the HMAC key with the given access ID.
func activateHMACKey(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.

	handle := client.HMACKeyHandle(projectID, accessID)
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()
	key, err := handle.Update(ctx, storage.HMACKeyAttrsToUpdate{State: "ACTIVE"})
	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

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Java API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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 ActivateHmacKey {
  public static void activateHmacKey(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.ACTIVE);

    System.out.println("The HMAC key is now active.");
    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

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Node.js API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

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

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

PHP

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage PHP API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\Cloud\Storage\StorageClient;

/**
 * Activate 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 activate_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('ACTIVE');

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

Python

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Python API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

from google.cloud import storage


def activate_key(access_id, project_id):
    """
    Activate the HMAC key with the given access ID.
    """
    # project_id = "Your Google Cloud project ID"
    # access_id = "ID of an inactive 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 = "ACTIVE"
    hmac_key.update()

    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

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Ruby API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

def activate_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.active!

  puts "The HMAC key is now active."
  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

Nächste Schritte

Informationen zum Suchen und Filtern von Codebeispielen für andere Google Cloud-Produkte finden Sie im Google Cloud-Beispielbrowser.