ניהול מפתחות HMAC לחשבונות שירות

סקירה כללית

בדף הזה מוסבר איך ליצור, להשבית ולמחוק מפתחות של קוד אימות הודעות (Hash-based Message Authentication Code או HMAC) שמבוססים על גיבוב (Hash), ושמשויכים לחשבונות שירות בפרויקט.

לפני שמתחילים

כדי להשתמש בתכונה הזו ב-Cloud Storage, צריך לעמוד בדרישות הבאות:

  1. הרשאה מספיקה כדי לעבוד עם מפתחות HMAC בפרויקט הרצוי:

    • אם אתם הבעלים של הפרויקט, סביר להניח שיש לכם את ההרשאות הדרושות.

    • אתם צריכים את הרשאות ה-IAM עם התחילית storage.hmacKeys עבור הפרויקט. במאמר שימוש בהרשאות IAM מוסבר איך מקבלים תפקיד עם ההרשאות האלה, כמו Storage HMAC Key Admin.

  2. אתם צריכים שיהיה לכם בפרויקט חשבון שירות שעבורו אתם מתכוונים ליצור את מפתחות ה-HMAC. אם אין לכם חשבון כזה, ראו את המאמר יצירת חשבון שירות.

  3. האילוץ restrictAuthTypes צריך להיות מושבת עבור אימות מפתח HMAC. להוראות איך לבדוק את האילוץ ואיך להשבית אותו, ראו את המאמר יצירה וניהול של מדיניות הארגון.

יצירת מפתח HMAC

כדי ליצור מפתח HMAC לחשבון שירות:

מסוף

  1. נכנסים לדף Settings של Cloud Storage במסוף Google Cloud.

    כניסה להגדרות

  2. בוחרים בכרטיסייה Interoperability.

  3. לוחצים על יצירת מפתח לחשבון שירות.

  4. בוחרים את חשבון השירות שאליו רוצים לשייך את מפתח ה-HMAC.

  5. לוחצים על יצירת מפתח.

להסבר איך לקבל מידע מפורט על שגיאות של פעולות Cloud Storage במסוף Google Cloud שנכשלו, ראו פתרון בעיות.

שורת הפקודה

gcloud

משתמשים בפקודה hmac create:

gcloud storage hmac create SERVICE_ACCOUNT_EMAIL

כאשר SERVICE_ACCOUNT_EMAIL היא כתובת האימייל שמשויכת לחשבון השירות שלכם. לדוגמה, service-7550275089395@my-pet-project.iam.gserviceaccount.com.

אם הפעולה בוצעה ללא שגיאות, התשובה תכיל משאב של מפתח HMAC, כולל הערכים של accessId ו-secret.

‏gsutil

משתמשים בפקודה hmac create:

gsutil hmac create SERVICE_ACCOUNT_EMAIL

כאשר SERVICE_ACCOUNT_EMAIL היא כתובת האימייל שמשויכת לחשבון השירות שלכם. לדוגמה, service-7550275089395@my-pet-project.iam.gserviceaccount.com.

אם הפעולה בוצעה בהצלחה, התשובה נראית כך:

AccessId: GOOGTS7C7FUP3AIRVJTE2BCDKINBTES3HC2GY5CBFJDCQ2SYHV6A6XXVTJFSA
SecretKey: de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9

ספריות לקוח

C++

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage C++ API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
return [](gcs::Client client, std::string const& service_account_email) {
  StatusOr<std::pair<gcs::HmacKeyMetadata, std::string>> key_info =
      client.CreateHmacKey(service_account_email);
  if (!key_info) throw std::move(key_info).status();

  std::cout << "The base64 encoded secret is: " << key_info->second
            << "\nDo not miss that secret, there is no API to recover it."
            << "\nThe HMAC key metadata is: " << key_info->first << "\n";
  return key_info->first.access_id();
}

C#

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage C# API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class CreateHmacKeySample
{
    public HmacKey CreateHmacKey(
        string projectId = "your-project-id",
        string serviceAccountEmail = "dev@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var key = storage.CreateHmacKey(projectId, serviceAccountEmail);

        var secret = key.Secret;
        var metadata = key.Metadata;

        Console.WriteLine($"The Base64 encoded secret is: {secret}");
        Console.WriteLine("Make sure to save that secret, there's no API to recover it.");
        Console.WriteLine("The HMAC key metadata is:");
        Console.WriteLine($"ID: {metadata.Id}");
        Console.WriteLine($"Access ID: {metadata.AccessId}");
        Console.WriteLine($"Project ID: {metadata.ProjectId}");
        Console.WriteLine($"Service Account Email: {metadata.ServiceAccountEmail}");
        Console.WriteLine($"State: {metadata.State}");
        Console.WriteLine($"Time Created: {metadata.TimeCreated}");
        Console.WriteLine($"Time Updated: {metadata.Updated}");
        Console.WriteLine($"ETag: {metadata.ETag}");
        return key;
    }
}

Go

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Go API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

// createHMACKey creates a new HMAC key using the given project and service account.
func createHMACKey(w io.Writer, projectID string, serviceAccountEmail 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()
	key, err := client.CreateHMACKey(ctx, projectID, serviceAccountEmail)
	if err != nil {
		return nil, fmt.Errorf("CreateHMACKey: %w", err)
	}

	fmt.Fprintf(w, "%s\n", key)
	fmt.Fprintf(w, "The base64 encoded secret is %s\n", key.Secret)
	fmt.Fprintln(w, "Do not miss that secret, there is no API to recover it.")
	fmt.Fprintln(w, "The HMAC key metadata is")
	fmt.Fprintf(w, "%+v", key)

	return key, nil
}

Java

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Java API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class CreateHmacKey {
  public static void createHmacKey(String serviceAccountEmail, String projectId)
      throws StorageException {

    // The service account email for which the new HMAC key will be created.
    // String serviceAccountEmail = "service-account@iam.gserviceaccount.com";

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

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

    ServiceAccount account = ServiceAccount.of(serviceAccountEmail);
    HmacKey hmacKey =
        storage.createHmacKey(account, Storage.CreateHmacKeyOption.projectId(projectId));

    String secret = hmacKey.getSecretKey();
    HmacKey.HmacKeyMetadata metadata = hmacKey.getMetadata();

    System.out.println("The Base64 encoded secret is: " + secret);
    System.out.println("Do not lose that secret, there is no API to recover it.");
    System.out.println("The HMAC key metadata is:");
    System.out.println("ID: " + metadata.getId());
    System.out.println("Access ID: " + metadata.getAccessId());
    System.out.println("Project ID: " + metadata.getProjectId());
    System.out.println("Service Account Email: " + metadata.getServiceAccount().getEmail());
    System.out.println("State: " + metadata.getState().toString());
    System.out.println("Time Created: " + new Date(metadata.getCreateTime()).toString());
    System.out.println("Time Updated: " + new Date(metadata.getUpdateTime()).toString());
    System.out.println("ETag: " + metadata.getEtag());
  }
}

Node.js

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Node.js API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The service account email for which the new HMAC key will be created
// const serviceAccountEmail = 'service-account@iam.gserviceaccount.com';

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

// Create HMAC SA Key
async function createHmacKey() {
  const [hmacKey, secret] = await storage.createHmacKey(serviceAccountEmail, {
    projectId,
  });

  console.log(`The base64 encoded secret is: ${secret}`);
  console.log('Do not miss that secret, there is no API to recover it.');
  console.log('The HMAC key metadata is:');
  for (const [key, value] of Object.entries(hmacKey.metadata)) {
    console.log(`${key}: ${value}`);
  }
}

PHP

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage PHP API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Storage\StorageClient;

/**
 * Create a new HMAC key.
 *
 * @param string $projectId The ID of your Google Cloud Platform project.
 *        (e.g. 'my-project-id')
 * @param string $serviceAccountEmail Service account email to associate with the new HMAC key.
 *        (e.g. 'service-account@iam.gserviceaccount.com')
 */
function create_hmac_key(string $projectId, string $serviceAccountEmail): void
{
    $storage = new StorageClient();
    // By default createHmacKey will use the projectId used by StorageClient().
    $hmacKeyCreated = $storage->createHmacKey($serviceAccountEmail, ['projectId' => $projectId]);

    printf('The base64 encoded secret is: %s' . PHP_EOL, $hmacKeyCreated->secret());
    print('Do not miss that secret, there is no API to recover it.' . PHP_EOL);
    printf('HMAC key Metadata: %s' . PHP_EOL, print_r($hmacKeyCreated->hmacKey()->info(), true));
}

Python

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Python API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import storage

def create_key(project_id, service_account_email):
    """
    Create a new HMAC key using the given project and service account.
    """
    # project_id = 'Your Google Cloud project ID'
    # service_account_email = 'Service account used to generate the HMAC key'

    storage_client = storage.Client(project=project_id)

    hmac_key, secret = storage_client.create_hmac_key(
        service_account_email=service_account_email, project_id=project_id
    )

    print(f"The base64 encoded secret is {secret}")
    print("Do not miss that secret, there is no API to recover it.")
    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

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Ruby API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

def create_hmac_key service_account_email:
  # The service account email used to generate an HMAC key
  # service_account_email = "service-my-project-number@gs-project-accounts.iam.gserviceaccount.com"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new

  # By default Storage#create_hmac_key uses the Storage client project_id
  hmac_key = storage.create_hmac_key service_account_email

  puts "The base64 encoded secret is: #{hmac_key.secret}"
  puts "Do not miss that secret, there is no API to recover it."
  puts "\nThe 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

Terraform

אתם יכולים להשתמש במשאב של Terraform כדי ליצור מפתח HMAC. הדוגמה הזו כוללת גם משאב ליצירת חשבון שירות.

# Create a new service account
resource "google_service_account" "service_account" {
  account_id = "my-svc-acc"
}

# Create the HMAC key for the associated service account
resource "google_storage_hmac_key" "key" {
  service_account_email = google_service_account.service_account.email
}

ממשקי API ל-REST

API ל-JSON

  1. מקבלים אסימון גישה להרשאה מ-OAuth 2.0 Playground. הגדירו את מגרש המשחקים כדי להשתמש בפרטי כניסה משלכם ל-OAuth. ההוראות מפורטות במאמר אימות API.
  2. משתמשים ב-cURL כדי לקרוא ל-API ל-JSON באמצעות בקשת POST hmacKeys:

    curl -X POST \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/storage/v1/projects/PROJECT_IDENTIFIER/hmacKeys?serviceAccountEmail=SERVICE_ACCOUNT_EMAIL"

    כאשר:

    • OAUTH2_TOKEN - אסימון הגישה שיצרתם בשלב 1.
    • PROJECT_IDENTIFIER - המזהה או המספר של הפרויקט שמשויך למפתח שרוצים ליצור. לדוגמה, my-pet-project.
    • SERVICE_ACCOUNT_EMAIL - כתובת האימייל שמשויכת לחשבון השירות שלכם. לדוגמה, service-7550275089395@my-pet-project.iam.gserviceaccount.com.

API ל-XML

  1. מקבלים אסימון גישה להרשאה מ-OAuth 2.0 Playground. הגדירו את מגרש המשחקים כדי להשתמש בפרטי כניסה משלכם ל-OAuth. ההוראות מפורטות במאמר אימות API.
  2. השתמשו ב-cURL כדי להפעיל את ה-API ל-XML באמצעות בקשת מפתח HMAC POST:

    curl -X POST \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/?Action=CreateAccessKey&UserName=SERVICE_ACCOUNT_EMAIL"

    כאשר:

    • OAUTH2_TOKEN - אסימון הגישה שיצרתם בשלב 1.
    • SERVICE_ACCOUNT_EMAIL - כתובת האימייל שמשויכת לחשבון השירות שלכם. לדוגמה, service-7550275089395@my-pet-project.iam.gserviceaccount.com.

קבלת מידע על מפתח HMAC

כדי לפרט את רשימת מפתחות ה-HMAC של פרויקט ולקבל מידע על המפתחות:

מסוף

  1. נכנסים לדף Settings של Cloud Storage במסוף Google Cloud.

    כניסה להגדרות

  2. בוחרים בכרטיסייה Interoperability.

שורת הפקודה

gcloud

  1. משתמשים בפקודה hmac list כדי לפרט את רשימת מפתחות hMac בפרויקט:

    gcloud storage hmac list

    אם הפעולה הסתיימה בהצלחה, הפקודה תחזיר רשימה של מזהי הגישה למפתחות hmac, יחד עם המצב של כל מפתח וחשבון השירות שמשויך לו.

  2. הפקודה hmac describe משמשת כדי לאחזר את המטא-נתונים של מפתח ספציפי:

    gcloud storage hmac describe KEY_ACCESS_ID 

    כאשר KEY_ACCESS_ID הוא מזהה הגישה של המפתח הרצוי.

‏gsutil

  1. משתמשים בפקודה hmac list כדי לפרט את רשימת מפתחות hMac בפרויקט:

    gsutil hmac list

    אם הפעולה הסתיימה בהצלחה, gsutil תחזיר רשימה של מזהי הגישה למפתחות hmac, יחד עם חשבון השירות שמשויך לכל מפתח.

  2. הפקודה hmac get משמשת כדי לאחזר את המטא-נתונים של מפתח ספציפי:

    gsutil hmac get KEY_ACCESS_ID 

    כאשר KEY_ACCESS_ID הוא מזהה הגישה של המפתח הרצוי.

ספריות לקוח

C++

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage C++ API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה מאחזרת רשימה של מפתחות HMAC המשויכים לפרויקט:

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";
  }
}

הדוגמה הבאה מאחזרת מידע של מפתח HMAC ספציפי:

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

  std::cout << "The HMAC key metadata is: " << *hmac_key << "\n";
}

C#

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage C# API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה מאחזרת רשימה של מפתחות HMAC המשויכים לפרויקט:


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;
    }
}

הדוגמה הבאה מאחזרת מידע של מפתח HMAC ספציפי:


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

public class GetHmacKeySample
{
    public HmacKeyMetadata GetHmacKey(
        string projectId = "your-project-id",
        string accessId = "your-access-id")
    {
        var storage = StorageClient.Create();
        var metadata = storage.GetHmacKey(projectId, accessId);

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

Go

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Go API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה מאחזרת רשימה של מפתחות HMAC המשויכים לפרויקט:

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
}

הדוגמה הבאה מאחזרת מידע של מפתח HMAC ספציפי:

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

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

// getHMACKey retrieves the HMACKeyMetadata with the given access id.
func getHMACKey(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.Get(ctx)
	if err != nil {
		return nil, fmt.Errorf("Get: %w", err)
	}

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

Java

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Java API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה מאחזרת רשימה של מפתחות HMAC המשויכים לפרויקט:


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

הדוגמה הבאה מאחזרת מידע של מפתח HMAC ספציפי:


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 GetHmacKey {
  public static void getHmacKey(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));

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

Node.js

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Node.js API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה מאחזרת רשימה של מפתחות HMAC המשויכים לפרויקט:

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

הדוגמה הבאה מאחזרת מידע של מפתח HMAC ספציפי:

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

// Get HMAC SA Key Metadata
async function getHmacKey() {
  const hmacKey = storage.hmacKey(hmacKeyAccessId, {projectId});

  // Populate the hmacKey object with metadata from server.
  await hmacKey.getMetadata();

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

PHP

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage PHP API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה מאחזרת רשימה של מפתחות HMAC המשויכים לפרויקט:

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']);
    }
}

הדוגמה הבאה מאחזרת מידע של מפתח HMAC ספציפי:

use Google\Cloud\Storage\StorageClient;

/**
 * Get 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 HMAC key. (e.g. 'GOOG0234230X00')
 */
function get_hmac_key(string $projectId, string $accessId): void
{
    $storage = new StorageClient();
    $hmacKey = $storage->hmacKey($accessId, $projectId);

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

Python

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Python API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה מאחזרת רשימה של מפתחות HMAC המשויכים לפרויקט:

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

הדוגמה הבאה מאחזרת מידע של מפתח HMAC ספציפי:

from google.cloud import storage

def get_key(access_id, project_id):
    """
    Retrieve the HMACKeyMetadata with the given access id.
    """
    # project_id = "Your Google Cloud project ID"
    # access_id = "ID of an HMAC key"

    storage_client = storage.Client(project=project_id)

    hmac_key = storage_client.get_hmac_key_metadata(
        access_id, project_id=project_id
    )

    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

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Ruby API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה מאחזרת רשימה של מפתחות HMAC המשויכים לפרויקט:

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

הדוגמה הבאה מאחזרת מידע של מפתח HMAC ספציפי:

def get_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

  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

ממשקי API ל-REST

API ל-JSON

  1. מקבלים אסימון גישה להרשאה מ-OAuth 2.0 Playground. הגדירו את מגרש המשחקים כדי להשתמש בפרטי כניסה משלכם ל-OAuth. ההוראות מפורטות במאמר אימות API.
  2. משתמשים ב-cURL כדי לקרוא ל-API ל-JSON באמצעות בקשת LIST hmacKeys:

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/projects/PROJECT_IDENTIFIER/hmacKeys"

    כאשר:

    • OAUTH2_TOKEN - אסימון הגישה שיצרתם בשלב 1.
    • PROJECT_IDENTIFIER - המזהה או המספר של הפרויקט שמשויך למפתחות שרוצים לרשום. לדוגמה, my-pet-project.

API ל-XML

  1. מקבלים אסימון גישה להרשאה מ-OAuth 2.0 Playground. הגדירו את מגרש המשחקים כדי להשתמש בפרטי כניסה משלכם ל-OAuth. ההוראות מפורטות במאמר אימות API.
  2. השתמשו ב-cURL כדי להפעיל את ה-API ל-XML באמצעות בקשת מפתח HMAC GET:

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/?Action=ListAccessKeys&UserName=SERVICE_ACCOUNT_EMAIL"

    כאשר:

    • OAUTH2_TOKEN - אסימון הגישה שיצרתם בשלב 1.
    • SERVICE_ACCOUNT_EMAIL - כתובת האימייל שמשויכת לחשבון השירות שלכם. לדוגמה, service-7550275089395@my-pet-project.iam.gserviceaccount.com.

עדכון המצב של מפתח HMAC

כדי להעביר מפתח HMAC בין מצב פעיל לבלתי פעיל:

מסוף

  1. נכנסים לדף Settings של Cloud Storage במסוף Google Cloud.

    כניסה להגדרות

  2. בוחרים בכרטיסייה Interoperability.

  3. לוחצים על השם של חשבון השירות שמשויך למפתח שרוצים לעדכן.

  4. לוחצים על התפריט more actions () שמשויך למפתח שרוצים לעדכן.

  5. בוחרים את המצב שרוצים להחיל על המפתח.

  6. בחלון האישור שמופיע, מאשרים שאתם רוצים לשנות את המצב של המפתח.

שורת הפקודה

gcloud

משתמשים בפקודה hmac update:

gcloud storage hmac update ACCESS_KEY_ID STATE

כאשר:

  • ACCESS_KEY_ID - מזהה הגישה שמשויך למפתח שמעדכנים.
  • STATE הוא --activate או --deactivate.

אם הפעולה מצליחה, הפקודה תחזיר את המטא-נתונים המעודכנים של מפתח ה-HMAC.

‏gsutil

משתמשים בפקודה hmac update:

gsutil hmac update -s STATE ACCESS_KEY_ID

כאשר:

  • STATE הוא המצב הרצוי של המפתח. לדוגמה, INACTIVE.
  • ACCESS_KEY_ID - מזהה הגישה שמשויך למפתח שמעדכנים.

אם הפעולה מצליחה, gsutil מחזירה את המטא-נתונים המעודכנים של מפתח ה-HMAC.

ספריות לקוח

C++

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage C++ API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה משביתה מפתח HMAC:

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";
}

הדוגמה הבאה מפעילה מפתח HMAC:

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#

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage C# API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה משביתה מפתח HMAC:


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;
    }
}

הדוגמה הבאה מפעילה מפתח HMAC:


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

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Go API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה משביתה מפתח HMAC:

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
}

הדוגמה הבאה מפעילה מפתח HMAC:

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

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Java API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה משביתה מפתח HMAC:


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

הדוגמה הבאה מפעילה מפתח HMAC:


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

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Node.js API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה משביתה מפתח HMAC:

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

הדוגמה הבאה מפעילה מפתח HMAC:

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

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage PHP API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה משביתה מפתח HMAC:

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

הדוגמה הבאה מפעילה מפתח HMAC:

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

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Python API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה משביתה מפתח HMAC:

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

הדוגמה הבאה מפעילה מפתח HMAC:

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

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Ruby API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הדוגמה הבאה משביתה מפתח HMAC:

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

הדוגמה הבאה מפעילה מפתח HMAC:

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

ממשקי API ל-REST

API ל-JSON

  1. מקבלים אסימון גישה להרשאה מ-OAuth 2.0 Playground. הגדירו את מגרש המשחקים כדי להשתמש בפרטי כניסה משלכם ל-OAuth. ההוראות מפורטות במאמר אימות API.
  2. יוצרים קובץ JSON שמכיל את הפרטים הבאים:

    {"state": "STATE"}

    כאשר STATE הוא המצב הרצוי למפתח. לדוגמה, INACTIVE.

  3. משתמשים ב-cURL כדי לקרוא ל-API ל-JSON באמצעות בקשת PUT hmacKeys:

    curl -X PUT --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/projects/PROJECT_IDENTIFIER/hmacKeys/ACCESS_KEY_ID"

    כאשר:

    • JSON_FILE_NAME הוא הנתיב לקובץ שיצרתם בשלב 2.
    • OAUTH2_TOKEN - אסימון הגישה שיצרתם בשלב 1.
    • PROJECT_IDENTIFIER - המזהה או המספר של הפרויקט שמשויך למפתח שרוצים לעדכן. לדוגמה, my-pet-project.
    • ACCESS_KEY_ID - מזהה הגישה שמשויך למפתח שמעדכנים.

API ל-XML

  1. מקבלים אסימון גישה להרשאה מ-OAuth 2.0 Playground. הגדירו את מגרש המשחקים כדי להשתמש בפרטי כניסה משלכם ל-OAuth. ההוראות מפורטות במאמר אימות API.
  2. השתמשו ב-cURL כדי להפעיל את ה-API ל-XML באמצעות בקשת מפתח HMAC POST:

    curl -X POST \
        -H "Authorization: Bearer OAUTH2_TOKEN" \
        "https://storage.googleapis.com/?Action=UpdateAccessKey&AccessKeyId=ACCESS_KEY_ID&Status=STATUS"

    כאשר:

    • OAUTH2_TOKEN - אסימון הגישה שיצרתם בשלב 1.
    • ACCESS_KEY_ID - מזהה הגישה שמשויך למפתח שמעדכנים.
    • STATUS הוא הסטטוס הרצוי של המפתח. לדוגמה, Inactive.

כשמשנים את המצב של מפתח HMAC, המצב החדש יופץ במערכת Cloud Storage תוך 3 דקות. לכן כדאי להמתין לפחות 3 דקות אחרי השבתת מפתח HMAC ולפני מחיקתו.

מחיקה של מפתח HMAC

כדי למחוק מפתח HMAC הוא צריך להיות במצב לא פעיל. כדי למחוק מפתח HMAC לא פעיל:

מסוף

  1. נכנסים לדף Settings של Cloud Storage במסוף Google Cloud.

    כניסה להגדרות

  2. בוחרים בכרטיסייה Interoperability.

  3. לוחצים על השם של חשבון השירות שמשויך למפתח שרוצים לעדכן.

  4. לוחצים על התפריט more actions () שמשויך למפתח שרוצים לעדכן.

  5. בתפריט הנפתח, בוחרים באפשרות Delete.

  6. בתיבת הטקסט שמופיעה, מזינים את 10 התווים הראשונים של מזהה מפתח הגישה, כפי שהם מופיעים בחלון.

  7. לוחצים על Delete.

שורת הפקודה

gcloud

משתמשים בפקודה hmac delete:

gcloud storage hmac delete ACCESS_KEY_ID

כאשר ACCESS_KEY_ID הוא מזהה הגישה שמשויך למפתח שרוצים למחוק.

אם הפעולה בוצעה בהצלחה, הפקודה לא תחזיר תשובה.

‏gsutil

משתמשים בפקודה hmac delete:

gsutil hmac delete ACCESS_KEY_ID

כאשר ACCESS_KEY_ID הוא מזהה הגישה שמשויך למפתח שרוצים למחוק.

אם הפעולה מצליחה, gsutil לא תחזיר תגובה.

ספריות לקוח

C++

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage C++ API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& access_id) {
  google::cloud::Status status = client.DeleteHmacKey(access_id);
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "The key is deleted, though it may still appear"
            << " in ListHmacKeys() results.\n";
}

C#

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage C# API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


using Google.Cloud.Storage.V1;
using System;

public class DeleteHmacKeySample
{
    public void DeleteHmacKey(
        string projectId = "your-project-id",
        string accessId = "your-access-id")
    {
        var storage = StorageClient.Create();
        storage.DeleteHmacKey(projectId, accessId);

        Console.WriteLine($"Key {accessId} was deleted.");
    }
}

Go

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Go API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

// deleteHMACKey deletes the HMAC key with the given access ID. Key must have state
// INACTIVE in order to succeed.
func deleteHMACKey(w io.Writer, accessID string, projectID string) error {
	ctx := context.Background()

	// Initialize client.
	client, err := storage.NewClient(ctx)
	if err != nil {
		return 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()
	if err = handle.Delete(ctx); err != nil {
		return fmt.Errorf("Delete: %w", err)
	}

	fmt.Fprintln(w, "The key is deleted, though it may still appear in ListHMACKeys results.")

	return nil
}

Java

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Java API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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 DeleteHmacKey {
  public static void deleteHmacKey(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));
    storage.deleteHmacKey(metadata);

    System.out.println(
        "The key is deleted, though it will still appear in "
            + "getHmacKeys() results if called with showDeletedKey.");
  }
}

Node.js

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Node.js API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

// Delete HMAC SA Key
async function deleteHmacKey() {
  const hmacKey = storage.hmacKey(hmacKeyAccessId, {projectId});
  await hmacKey.delete();

  console.log(
    'The key is deleted, though it may still appear in getHmacKeys() results.'
  );
}

PHP

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage PHP API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Storage\StorageClient;

/**
 * Delete 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 HMAC key. (e.g. 'GOOG0234230X00')
 */
function delete_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->delete();
    print(
        'The key is deleted, though it may still appear in the results of calls ' .
        'to StorageClient.hmacKeys([\'showDeletedKeys\' => true])' . PHP_EOL
    );
}

Python

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Python API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import storage

def delete_key(access_id, project_id):
    """
    Delete the HMAC key with the given access ID. Key must have state INACTIVE
    in order to succeed.
    """
    # project_id = "Your Google Cloud project ID"
    # access_id = "ID of an HMAC key (must be in INACTIVE state)"

    storage_client = storage.Client(project=project_id)

    hmac_key = storage_client.get_hmac_key_metadata(
        access_id, project_id=project_id
    )
    hmac_key.delete()

    print(
        "The key is deleted, though it may still appear in list_hmac_keys()"
        " results."
    )

Ruby

למידע נוסף, תוכלו לקרוא את חומרי העזר של Cloud Storage Ruby API.

כדי לאמת ב-Cloud Storage, יש להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

def delete_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.delete!

  puts "The key is deleted, though it may still appear in Client#hmac_keys results."
end

ממשקי API ל-REST

API ל-JSON

  1. מקבלים אסימון גישה להרשאה מ-OAuth 2.0 Playground. הגדירו את מגרש המשחקים כדי להשתמש בפרטי כניסה משלכם ל-OAuth. ההוראות מפורטות במאמר אימות API.
  2. משתמשים ב-cURL כדי לקרוא ל-API ל-JSON באמצעות בקשת DELETE hmacKeys:

    curl -X DELETE \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/storage/v1/projects/PROJECT_IDENTIFIER/hmacKeys/ACCESS_KEY_ID"

    כאשר:

    • OAUTH2_TOKEN - אסימון הגישה שיצרתם בשלב 1.
    • PROJECT_IDENTIFIER המזהה או המספר של הפרויקט שמשויך למפתח שרוצים למחוק. לדוגמה, my-pet-project.
    • ACCESS_KEY_ID מזהה הגישה שמשויך למפתח שמוחקים.

API ל-XML

  1. מקבלים אסימון גישה להרשאה מ-OAuth 2.0 Playground. הגדירו את מגרש המשחקים כדי להשתמש בפרטי כניסה משלכם ל-OAuth. ההוראות מפורטות במאמר אימות API.
  2. השתמשו ב-cURL כדי להפעיל את ה-API ל-XML באמצעות בקשת מפתח HMAC POST:

    curl -X POST \
        -H "Authorization: Bearer OAUTH2_TOKEN" \
        "https://storage.googleapis.com/?Action=DeleteAccessKey&AccessKeyId=ACCESS_KEY_ID"

    כאשר:

    • OAUTH2_TOKEN - אסימון הגישה שיצרתם בשלב 1.
    • ACCESS_KEY_ID מזהה הגישה שמשויך למפתח שמוחקים.

המאמרים הבאים