以下示例演示如何通过 Temporary Credentials API 和本地客户端签名生成 R2 临时凭据,以及如何使用生成的凭据与 S3 客户端配合。
- 父级 R2 API 令牌,至少具有您计划委托的权限。切勿将父级凭据发送给客户端。
- 您的 Cloudflare 账户 ID。
- 支持会话令牌的 S3 客户端。以下示例使用 aws4fetch ↗。
从受信任的服务器调用 Temporary Credentials API,然后使用返回的凭据与任何 S3 客户端配合。
curl https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/r2/temp-access-credentials \
--header "Authorization: Bearer <PARENT_API_TOKEN>" \
--header "Content-Type: application/json" \
--data '{
"bucket": "my-bucket",
"parentAccessKeyId": "<PARENT_ACCESS_KEY_ID>",
"permission": "object-read-only",
"ttlSeconds": 900,
"objects": ["reports/2026-q1.pdf"]
}'响应将凭据包装在 result 对象中:
{
"result": {
"accessKeyId": "<accessKeyId>",
"secretAccessKey": "<secretAccessKey>",
"sessionToken": "<sessionToken>"
},
"errors": [],
"messages": [],
"success": true
}此示例使用 jose ↗ 签名 JWT,使用 aws4fetch ↗ 发出签名请求。
npm i jose aws4fetchyarn add jose aws4fetchpnpm add jose aws4fetchbun add jose aws4fetch以下辅助函数使用父级 secret access key 签名 JWT,并派生临时 secret access key 和 session token:
import { SignJWT } from "jose";
type R2Scope =
| "object-read-only"
| "object-read-write"
| "admin-read-only"
| "admin-read-write";
export interface TempCredentialOptions {
scope: R2Scope;
// Optional: narrow the credential to specific S3 operations.
actions?: string[];
// Time-to-live in seconds. Defaults to 1 hour.
ttlSeconds?: number;
// Optional: restrict access to specific prefixes or objects.
paths?: { prefixPaths?: string[]; objectPaths?: string[] };
}
export async function createTempCredentials(
endpoint: string,
accountId: string,
parentAccessKeyId: string,
parentSecretAccessKey: string,
bucket: string,
opts: TempCredentialOptions,
): Promise<{
accessKeyId: string;
secretAccessKey: string;
sessionToken: string;
}> {
const ttl = opts.ttlSeconds ?? 3600;
const claims: Record<string, unknown> = {
bucket,
scope: opts.scope,
};
if (opts.actions !== undefined && opts.actions.length > 0) {
claims.actions = opts.actions;
}
if (opts.paths !== undefined) {
claims.paths = {
prefixPaths: opts.paths.prefixPaths ?? [],
objectPaths: opts.paths.objectPaths ?? [],
};
}
// Sign the JWT with the parent secret access key. R2 validates this signature.
const jwt = await new SignJWT(claims)
.setProtectedHeader({ alg: "HS256", typ: "JWT" })
.setSubject(accountId)
.setIssuer(parentAccessKeyId)
.setAudience(new URL(endpoint).host)
.setIssuedAt()
.setExpirationTime(`${ttl}s`)
.sign(new TextEncoder().encode(parentSecretAccessKey));
// The temporary secret access key is the SHA-256 hex digest of the signed JWT.
const digest = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode(jwt),
);
const secretAccessKey = Array.from(new Uint8Array(digest))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
return {
// Reuse the parent access key ID as the temporary access key ID.
accessKeyId: parentAccessKeyId,
secretAccessKey,
// The session token is base64("jwt/" + signed JWT).
sessionToken: btoa(`jwt/${jwt}`),
};
}以下示例返回有效期为 15 分钟且只能对 data/ 前缀执行 GetObject 和 HeadObject 的凭据:
import { createTempCredentials } from "./temp-credentials";
const R2_URL = `https://${ACCOUNT_ID}.r2.cloudflarestorage.com`;
const creds = await createTempCredentials(
R2_URL,
ACCOUNT_ID,
PARENT_ACCESS_KEY_ID,
PARENT_SECRET_ACCESS_KEY,
"my-bucket",
{
scope: "object-read-only",
actions: ["GetObject", "HeadObject"],
ttlSeconds: 900,
paths: { prefixPaths: ["data/"] },
},
);获得临时凭据后,无论生成方式如何,用法都相同。将三个值传递给 S3 客户端并发出请求。以下示例使用限定在 data/ 前缀的凭据,演示一个允许和一个被拒绝的请求:
import { AwsClient } from "aws4fetch";
const R2_URL = `https://${ACCOUNT_ID}.r2.cloudflarestorage.com`;
const client = new AwsClient({
accessKeyId: ACCESS_KEY_ID,
secretAccessKey: SECRET_ACCESS_KEY,
sessionToken: SESSION_TOKEN,
service: "s3",
});
// Allowed: object under the data/ prefix.
const ok = await client.fetch(`${R2_URL}/my-bucket/data/file.bin`);
console.log(ok.status); // 200
// Rejected with 403 AccessDenied because the object is outside the data/ prefix.
const denied = await client.fetch(`${R2_URL}/my-bucket/other/file.bin`);
console.log(denied.status); // 403