使用 Cloud Storage 工具执行 V4 签名流程

本页面介绍如何使用 gsutil 和 Cloud Storage 客户端库轻松生成签名网址。签名网址可提供带有时限的读取或写入访问权限,供用户访问特定的 Cloud Storage 资源。拥有签名网址的任何人都可以在其有效时限内使用该网址,无论是否有 Google 帐号。如需详细了解签名网址,请参阅签名网址概览。如需自行创建签名网址,请参阅使用自己的程序执行 V4 签名流程

如需生成签名网址,请执行以下操作:

gsutil

  1. 生成新的私钥,或使用现有私钥作为服务帐号。密钥可以是 JSON 或 PKCS12 格式。

    如需详细了解私钥和服务帐号,请参阅服务帐号

  2. 使用 gsutil signurl 命令,传入上一步中的私钥路径,以及要为其生成签名网址的存储分区或对象的名称。

    例如,使用存储在 Desktop 文件夹中的密钥,以下命令会生成一个签名网址,供用户在 10 分钟的时间内查看对象 cat.jpeg

    gsutil signurl -d 10m Desktop/private-key.json gs://example-bucket/cat.jpeg

如果成功,响应应如下所示:

URL    HTTP Method    Expiration    Signed URL
gs://example-bucket/cat.jpeg GET 2018-10-26 15:19:52 https://storage.googleapis.
com/example-bucket/cat.jpeg?x-goog-signature=2d2a6f5055eb004b8690b9479883292ae74
50cdc15f17d7f99bc49b916f9e7429106ed7e5858ae6b4ab0bbbdb1a8ccc364dad3a0da2caebd308
87a70c5b2569d089ceb8afbde3eed4dff5086f0db5483998c175980991fe899fbd2cd8cb813b0016
5e8d56e0a8aa7b3d7a12ee1baa8400611040f05b50a1a8eab5ba223fe1375747748de950ec7a4dc5
0f8382a6ffd4994ac42498d7daa703d9a414d4475154d0e7edaa92d4f2507d92c1f7e8efa7cab64d
f68b5df48575b9259d8d0bdb5dc752bdf07bd162d98ff2924f2e4a26fa6b3cede73ad5333c47d146
a21c2ab2d97115986a12c68ff37346d6c2ca83e56b8ec8ad95632710b489b75c35697d781c38e&
x-goog-algorithm=GOOG4-RSA-SHA256&x-goog-credential=example%40example-project.
iam.gserviceaccount.com%2F20181026%2Fus%2Fstorage%2Fgoog4_request&x-goog-date=
20181026T211942Z&x-goog-expires=3600&x-goog-signedheaders=host

签名网址是以 https://storage.googleapis.com 开头的字符串(可能会包括多行)。此网址可供任何人用来在指定时间范围内(在本例中为 10 分钟)访问相关资源(在本例中为 cat.jpeg)。

代码示例

以下示例专门展示了如何创建可从 Cloud Storage 获取对象的签名网址。

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string object_name) {
  StatusOr<std::string> signed_url = client.CreateV4SignedUrl(
      "GET", std::move(bucket_name), std::move(object_name),
      gcs::SignedUrlDuration(std::chrono::minutes(15)));

  if (!signed_url) {
    throw std::runtime_error(signed_url.status().message());
  }

  std::cout << "The signed url is: " << *signed_url << "\n\n"
            << "You can use this URL with any user agent, for example:\n"
            << "curl '" << *signed_url << "'\n";
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

private void GenerateV4SignedGetUrl(string bucketName, string objectName)
{
    UrlSigner urlSigner = UrlSigner
        .FromServiceAccountPath(Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS"))
        .WithSigningVersion(SigningVersion.V4);
    string url = urlSigner.Sign(bucketName, objectName, TimeSpan.FromHours(1), HttpMethod.Get);
    Console.WriteLine("Generated GET signed URL:");
    Console.WriteLine(url);
    Console.WriteLine("You can use this URL with any user agent, for example:");
    Console.WriteLine($"curl '{url}'");
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

jsonKey, err := ioutil.ReadFile(serviceAccount)
if err != nil {
	return "", fmt.Errorf("cannot read the JSON key file, err: %v", err)
}

conf, err := google.JWTConfigFromJSON(jsonKey)
if err != nil {
	return "", fmt.Errorf("google.JWTConfigFromJSON: %v", err)
}

opts := &storage.SignedURLOptions{
	Scheme:         storage.SigningSchemeV4,
	Method:         "GET",
	GoogleAccessID: conf.Email,
	PrivateKey:     conf.PrivateKey,
	Expires:        time.Now().Add(15 * time.Minute),
}

u, err := storage.SignedURL(bucketName, objectName, opts)
if err != nil {
	return "", fmt.Errorf("Unable to generate a signed URL: %v", err)
}

fmt.Fprintln(w, "Generated GET signed URL:")
fmt.Fprintf(w, "%q\n", u)
fmt.Fprintln(w, "You can use this URL with any user agent, for example:")
fmt.Fprintf(w, "curl %q\n", u)

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

// The name of an object, e.g. "my-object"
// String objectName = "my-object";

// Define resource
BlobInfo blobinfo = BlobInfo.newBuilder(BlobId.of(bucketName, objectName)).build();

// Generate Signed URL
URL url =
    storage.signUrl(blobinfo, 15, TimeUnit.MINUTES, Storage.SignUrlOption.withV4Signature());

System.out.println("Generated GET signed URL:");
System.out.println(url);
System.out.println("You can use this URL with any user agent, for example:");
System.out.println("curl '" + url + "'");

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to access, e.g. file.txt';

// These options will allow temporary read access to the file
const options = {
  version: 'v4',
  action: 'read',
  expires: Date.now() + 15 * 60 * 1000, // 15 minutes
};

// Get a v4 signed URL for reading the file
const [url] = await storage
  .bucket(bucketName)
  .file(filename)
  .getSignedUrl(options);

console.log('Generated GET signed URL:');
console.log(url);
console.log('You can use this URL with any user agent, for example:');
console.log(`curl '${url}'`);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

use Google\Cloud\Storage\StorageClient;

/**
 * Generate a v4 signed URL for downloading an object.
 *
 * @param string $bucketName the name of your Google Cloud bucket.
 * @param string $objectName the name of your Google Cloud object.
 *
 * @return void
 */
function get_object_v4_signed_url($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $url = $object->signedUrl(
        # This URL is valid for 15 minutes
        new \DateTime('15 min'),
        [
            'version' => 'v4',
        ]
    );

    print('Generated GET signed URL:' . PHP_EOL);
    print($url . PHP_EOL);
    print('You can use this URL with any user agent, for example:' . PHP_EOL);
    print('curl ' . $url . PHP_EOL);
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

def generate_download_signed_url_v4(bucket_name, blob_name):
    """Generates a v4 signed URL for downloading a blob.

    Note that this method requires a service account key file. You can not use
    this if you are using Application Default Credentials from Google Compute
    Engine or from the Google Cloud SDK.
    """
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(blob_name)

    url = blob.generate_signed_url(
        version='v4',
        # This URL is valid for 15 minutes
        expiration=datetime.timedelta(minutes=15),
        # Allow GET requests using this URL.
        method='GET')

    print('Generated GET signed URL:')
    print(url)
    print('You can use this URL with any user agent, for example:')
    print('curl \'{}\''.format(url))
    return url

此页内容是否有用?请给出您的反馈和评价:

发送以下问题的反馈:

此网页
Cloud Storage
需要帮助?请访问我们的支持页面