본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

R2 임시 자격 증명으로 인증하기 (Authenticate against R2 with temporary credentials)

원문 보기 위키 갱신

Temporary Credentials API와 로컬 클라이언트 측 서명을 통해 임시 자격 증명을 생성하고, 그 결과 자격 증명을 S3 클라이언트와 함께 사용하는 방법을 보여드려요.

출처: 문서

본문

다음 예시들은 Temporary Credentials API와 로컬 클라이언트 측 서명, 두 방법 모두를 통해 R2 임시 자격 증명을 생성하고, 결과 자격 증명을 S3 클라이언트와 함께 사용하는 방법을 보여줘요.

전제 조건 (Prerequisites)

  • 위임할 권한을 최소한 갖춘 상위(parent) R2 API 토큰. 상위 자격 증명을 클라이언트에 절대 배포하지 마세요.
  • Cloudflare 계정 ID.
  • 세션 토큰을 지원하는 S3 클라이언트. 아래 예시는 aws4fetch ↗︎를 사용해요.

Temporary Credentials API로 생성하기 (Generate via the Temporary Credentials API)

신뢰할 수 있는 서버에서 Temporary Credentials API를 호출한 다음, 반환된 자격 증명을 아무 S3 클라이언트와 함께 사용하세요.

curl https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/r2/temp-access-credentials \
  --header "Authorization: Bearer <PAREN...KEN>" \
  --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
}

로컬에서 생성하기(클라이언트 측 서명) (Generate locally (client-side signing))

이 예시는 JWT 서명에 jose ↗︎를, 서명된 요청 발행에 aws4fetch ↗︎를 사용해요.

npm:

npm i jose aws4fetch

yarn:

yarn add jose aws4fetch

pnpm:

pnpm add jose aws4fetch

bun:

bun add jose aws4fetch

다음 헬퍼는 상위 secret access key로 JWT에 서명하고, 임시 secret access key와 세션 토큰을 도출해요:

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/"] },
  },
);

자격 증명 사용하기 (Use the credentials)

임시 자격 증명을 얻고 나면, 생성 방법과 관계없이 사용법은 동일해요. 세 값을 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

더 알아보기 (Learn more)