跳转到内容
搜索文档

aws4fetch

最后更新 查看 MarkdownAgent 设置

在开始之前,您必须生成 Access Key。所有示例都将使用 access_key_idaccess_key_secret 变量,分别代表您生成的 Access Key ID(访问密钥 ID)Secret Access Key(秘密访问密钥) 值。


JavaScript 或 TypeScript 用户可以继续照常使用 aws4fetch npm 包。此包使用 fetchSubtleCrypto API,在浏览器或 Cloudflare Workers 中工作时您会很熟悉。

实例化 S3 服务客户端时,必须传入 R2 配置凭据:

import { AwsClient } from "aws4fetch";

// Provide your Cloudflare account ID
const R2_URL = `https://${ACCOUNT_ID}.r2.cloudflarestorage.com`;

const client = new AwsClient({
	// Retrieve your S3 API credentials for your R2 bucket via API tokens (see: https://developers.cloudflare.com/r2/api/tokens)
	accessKeyId: ACCESS_KEY_ID,
	secretAccessKey: SECRET_ACCESS_KEY,
});

const ListBucketsResult = await client.fetch(R2_URL);
console.log(await ListBucketsResult.text());
// <ListAllMyBucketsResult>
//     <Buckets>
//         <Bucket>
//             <CreationDate>2022-04-13T21:23:47.102Z</CreationDate>
//             <Name>user-uploads</Name>
//         </Bucket>
//         <Bucket>
//             <CreationDate>2022-05-07T02:46:49.218Z</CreationDate>
//             <Name>my-bucket</Name>
//         </Bucket>
//     </Buckets>
//     <Owner>
//         <DisplayName>...</DisplayName>
//         <ID>...</ID>
//     </Owner>
// </ListAllMyBucketsResult>

const ListObjectsV2Result = await client.fetch(
	`${R2_URL}/my-bucket?list-type=2`,
);
console.log(await ListObjectsV2Result.text());
// <ListBucketResult>
//   <Name>my-bucket</Name>
//   <Contents>
//     <Key>cat.png</Key>
//     <Size>751832</Size>
//     <LastModified>2022-05-07T02:50:45.616Z</LastModified>
//     <ETag>"c4da329b38467509049e615c11b0c48a"</ETag>
//     <StorageClass>STANDARD</StorageClass>
//   </Contents>
//   <Contents>
//     <Key>todos.txt</Key>
//     <Size>278</Size>
//     <LastModified> 2022-05-07T21:37:17.150Z</LastModified>
//     <ETag>"29d911f495d1ba7cb3a4d7d15e63236a"</ETag>
//     <StorageClass>STANDARD</StorageClass>
//   </Contents>
//   <IsTruncated>false</IsTruncated>
//   <MaxKeys>1000</MaxKeys>
//   <KeyCount>2</KeyCount>
// </ListBucketResult>

生成预签名 URL

您还可以生成预签名链接,以便临时共享存储桶的公开读取或写入访问权限。

import { AwsClient } from "aws4fetch";

const client = new AwsClient({
	service: "s3", // Required by SDK but not used by R2
	region: "auto", // Required by SDK but not used by R2
	// Retrieve your S3 API credentials for your R2 bucket via API tokens (see: https://developers.cloudflare.com/r2/api/tokens)
	accessKeyId: ACCESS_KEY_ID,
	secretAccessKey: SECRET_ACCESS_KEY,
});

// Provide your Cloudflare account ID
const R2_URL = `https://${ACCOUNT_ID}.r2.cloudflarestorage.com`;

// Use the `X-Amz-Expires` query param to determine how long the presigned link is valid.
console.log(
	(
		await client.sign(
			new Request(`${R2_URL}/my-bucket/dog.png?X-Amz-Expires=${3600}`),
			{
				aws: { signQuery: true },
			},
		)
	).url.toString(),
);
// You can also create links for operations such as PutObject to allow temporary write access to a specific key.
// Specify Content-Type header to restrict uploads to a specific file type.
console.log(
	(
		await client.sign(
			new Request(`${R2_URL}/my-bucket/dog.png?X-Amz-Expires=${3600}`, {
				method: "PUT",
				headers: {
					"Content-Type": "image/png",
				},
			}),
			{
				aws: { signQuery: true },
			},
		)
	).url.toString(),
);
https://<ACCOUNT_ID>.r2.cloudflarestorage.com/my-bucket/dog.png?X-Amz-Expires=3600&X-Amz-Date=<timestamp>&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credential>&X-Amz-SignedHeaders=host&X-Amz-Signature=<signature>
https://<ACCOUNT_ID>.r2.cloudflarestorage.com/my-bucket/dog.png?X-Amz-Expires=3600&X-Amz-Date=<timestamp>&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credential>&X-Amz-SignedHeaders=content-type%3Bhost&X-Amz-Signature=<signature>

您可以使用 PutObject 示例生成的链接,在预签名链接过期之前向指定的存储桶和键上传对象。使用带有 Content-Type 的预签名 URL 时,客户端必须包含匹配的 Content-Type 请求头。

curl -X PUT "https://<ACCOUNT_ID>.r2.cloudflarestorage.com/my-bucket/dog.png?X-Amz-Expires=3600&X-Amz-Date=<timestamp>&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credential>&X-Amz-SignedHeaders=content-type%3Bhost&X-Amz-Signature=<signature>" \
  -H "Content-Type: image/png" \
  --data-binary @dog.png

使用 CORS 和 Content-Type 限制上传

生成用于上传的预签名 URL 时,您可以通过以下方式限制滥用和误用:

  1. 限制 Content-Type:在签名时于请求中指定 Content-Type 请求头。如果客户端发送不同的 Content-Type 请求头,上传将失败。

  2. 配置 CORS:在存储桶上设置 CORS 规则,以控制哪些源可以上传文件。通过 Cloudflare 仪表板 向存储桶设置添加 JSON 策略来配置 CORS:

[
  {
    "AllowedOrigins": ["https://example.com"],
    "AllowedMethods": ["PUT"],
    "AllowedHeaders": ["Content-Type"],
    "ExposeHeaders": ["ETag"],
    "MaxAgeSeconds": 3600
  }
]

然后生成带有 Content-Type 限制的预签名 URL:

const signedRequest = await client.sign(
	new Request(`${R2_URL}/my-bucket/user-upload.png?X-Amz-Expires=${3600}`, {
		method: "PUT",
		headers: {
			"Content-Type": "image/png",
		},
	}),
	{
		aws: { signQuery: true },
	},
);
const putUrl = signedRequest.url.toString();

客户端使用此预签名 URL 时必须:

  • 从允许的源发起请求(由 CORS 强制执行)
  • 包含 Content-Type: image/png 请求头(由签名强制执行)

这篇文档对您有帮助吗?