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

R2 API 인증 토큰으로 인증하기 (Authenticate against R2 API using auth tokens)

원문 보기 위키 갱신

Python 또는 JavaScript에서 API 토큰을 사용해 R2 S3 호환 API에 인증하는 방법을 보여드려요.

출처: 문서

본문

다음 예시는 S3 API와 API 토큰을 사용해 R2에 인증하는 방법을 보여줘요.

참고

익명 사용자에게 버킷 객체에 대한 보안 접근을 제공하려면 사전 서명 URL(pre-signed URLs)을 사용하는 것을 권장해요.

사전 서명 URL은 사용자가 조직의 구성원일 필요가 없으며, R2에 대한 직접적인 프로그램 접근을 가능하게 해요.

어느 예시를 실행하기 전에 다음 환경 변수를 설정했는지 확인하세요. 자세한 내용은 인증(Authentication)을 참고하세요.

export AWS_REGION=auto
export AWS_ENDPOINT_URL=https://<account_id>.r2.cloudflarestorage.com
export AWS_ACCESS_KEY_ID=your_access_key_id
export AWS_SECRET_ACCESS_KEY=your_secret_access_key

JavaScript (Node.js)

S3 API용 @aws-sdk/client-s3 패키지를 설치하세요:

npm:

npm i @aws-sdk/client-s3

yarn:

yarn add @aws-sdk/client-s3

pnpm:

pnpm add @aws-sdk/client-s3

bun:

bun add @aws-sdk/client-s3

node index.js로 다음 Node.js 스크립트를 실행하세요. Bucket을 자신의 버킷 이름으로, Key를 R2 버킷에 있는 기존 파일을 가리키도록 바꾸세요.

아래 튜토리얼은 TypeScript에서도 동작해야 한다는 점을 참고하세요.

import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";

const s3 = new S3Client();

const Bucket = "<YOUR_BUCKET_NAME>";
const Key = "pfp.jpg";

const object = await s3.send(
  new GetObjectCommand({
    Bucket,
    Key,
  }),
);

console.log("Successfully fetched the object", object.$metadata);

// Process the data as needed
// For example, to get the content as a Buffer:
// const content = data.Body;

// Or to save the file (requires 'fs' module):
// import { writeFile } from "node:fs/promises";
// await writeFile('ingested_0001.parquet', data.Body);

Python

boto3 S3 API 클라이언트를 설치하세요:

pip install boto3

python3 get_r2_object.py로 다음 Python 스크립트를 실행하세요. bucket을 자신의 버킷 이름으로, object_key를 R2 버킷에 있는 기존 파일을 가리키도록 바꾸세요.

import boto3
from botocore.client import Config

# Configure the S3 client for Cloudflare R2
s3_client = boto3.client('s3',
  config=Config(signature_version='s3v4')
)

# Specify the object key
#
bucket = '<YOUR_BUCKET_NAME>'
object_key = '2024/08/02/ingested_0001.parquet'

try:
  # Fetch the object
  response = s3_client.get_object(Bucket=bucket, Key=object_key)

  print('Successfully fetched the object')

  # Process the response content as needed
  # For example, to read the content:
  # object_content = response['Body'].read()

  # Or to save the file:
  # with open('ingested_0001.parquet', 'wb') as f:
  #     f.write(response['Body'].read())

except Exception as e:
  print(f'Failed to fetch the object. Error: {str(e)}')

Go

go get을 사용해 Go 프로젝트에 aws-sdk-go-v2 패키지들을 추가하세요:

go get github.com/aws/aws-sdk-go-v2
go get github.com/aws/aws-sdk-go-v2/config
go get github.com/aws/aws-sdk-go-v2/credentials
go get github.com/aws/aws-sdk-go-v2/service/s3

go run main.go로 다음 Go 애플리케이션을 스크립트로 실행하세요. bucket을 자신의 버킷 이름으로, objectKey를 R2 버킷에 있는 기존 파일을 가리키도록 바꾸세요.

package main

import (
  "context"
  "fmt"
  "io"
  "log"
  "github.com/aws/aws-sdk-go-v2/aws"
  "github.com/aws/aws-sdk-go-v2/config"
  "github.com/aws/aws-sdk-go-v2/service/s3"
)

func main() {
    cfg, err := config.LoadDefaultConfig(context.TODO())
    if err != nil {
	    log.Fatalf("Unable to load SDK config, %v", err)
    }

    // Create an S3 client
    client := s3.NewFromConfig(cfg)

    // Specify the object key
    bucket := "<YOUR_BUCKET_NAME>"
    objectKey := "pfp.jpg"

    // Fetch the object
    output, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
	    Bucket: aws.String(bucket),
	    Key:    aws.String(objectKey),
    })
    if err != nil {
	    log.Fatalf("Unable to fetch object, %v", err)
    }
    defer output.Body.Close()

    fmt.Println("Successfully fetched the object")

    // Process the object content as needed
    // For example, to save the file:
    // file, err := os.Create("ingested_0001.parquet")
    // if err != nil {
    // 	log.Fatalf("Unable to create file, %v", err)
    // }
    // defer file.Close()
    // _, err = io.Copy(file, output.Body)
    // if err != nil {
    // 	log.Fatalf("Unable to write file, %v", err)
    // }

    // Or to read the content:
    content, err := io.ReadAll(output.Body)
    if err != nil {
	    log.Fatalf("Unable to read object content, %v", err)
    }
    fmt.Printf("Object content length: %d bytes\n", len(content))
}

더 알아보기 (Learn more)