0Pricing
Edge Computing with Cloudflare Workers & Deno · 강의

인증 및 권한 부여

엣지 API 엔드포인트를 보호하기 위한 사용자 인증 및 권한 부여 전략을 구현합니다.

인증 및 권한 부여은(는) CoddyKit의 무료 Edge Computing with Cloudflare Workers & Deno 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Edge Computing with Cloudflare Workers & Deno 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Securing Edge APIs

Welcome! In this lesson, we'll dive into Authentication and Authorization for your edge API endpoints.

These are crucial concepts for protecting your applications and ensuring only the right users can access specific resources.

AuthN vs. AuthZ

Let's clarify two key terms:

  • Authentication (AuthN): Verifies who you are. Think of it like showing your ID to prove your identity.
  • Authorization (AuthZ): Determines what you can do. This is like your ID granting you access to certain areas, but not others.

They often work together, but are distinct processes.

Common Edge Auth Methods

At the edge, we need lightweight and efficient authentication methods. Common approaches include:

  • API Keys: Simple secrets used to identify an application or user.
  • JSON Web Tokens (JWTs): Self-contained, digitally signed tokens for secure information exchange.
  • OAuth/OIDC: More complex protocols for delegated authorization, often relying on JWTs.

We'll focus on API Keys and JWTs.

Implementing API Key Auth

API Keys are straightforward. A client sends a secret key, usually in a header, and your Worker validates it. Let's see a simple example:

export default {
  async fetch(request, env, ctx) {
    const apiKey = request.headers.get('X-API-Key');

    // In a real app, fetch 'MY_API_KEY' from env.MY_API_KEY
    if (apiKey !== 'super-secret-key-123') {
      return new Response('Unauthorized: Invalid API Key', { status: 401 });
    }

    return new Response('Access Granted!', { status: 200 });
  },
};

API Key Auth Explained

In the example, the Worker checks for the X-API-Key header. If it doesn't match our expected secret, access is denied with a 401 Unauthorized status.

For production, always store your API keys securely, typically in Cloudflare Worker environment variables, not directly in your code.

JSON Web Tokens (JWTs)

JWTs are powerful for edge applications because they are self-contained. Once issued by an identity provider, a JWT can be verified by your Worker without needing to contact a central server every time.

A JWT has three parts: Header, Payload, and Signature, separated by dots.

Verifying JWTs on the Edge

Your Worker will receive a JWT, usually in the Authorization: Bearer header. The critical step is to verify its signature to ensure it hasn't been tampered with.

While full cryptographic verification requires a library, here's where you'd typically extract and prepare for verification:

export default {
  async fetch(request, env, ctx) {
    const authHeader = request.headers.get('Authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return new Response('Unauthorized: No token', { status: 401 });
    }

    const token = authHeader.split(' ')[1];

    // In a real app, you'd use a crypto library and a secret key
    // to verify the token's signature, expiry, and claims.
    // e.g., using 'jose' library with `await jwtVerify(token, secretKey)`
    if (token) {
      // For this example, we'll assume a successful (mock) verification
      return new Response('Access Granted with JWT!', { status: 200 });
    }

    return new Response('Unauthorized: Invalid JWT', { status: 401 });
  },
};

Role-Based Authorization (RBAC)

Once a user is authenticated (e.g., via a verified JWT), you need to decide what actions they are authorized to perform. This is where Role-Based Access Control (RBAC) comes in.

RBAC assigns permissions to roles (e.g., 'admin', 'user', 'guest'), and users are assigned one or more roles. Your Worker then checks the user's role before allowing an action.

Implementing RBAC in Worker

You can embed user roles or permissions directly into the JWT payload as 'claims'. After verifying the JWT, your Worker can read these claims and enforce authorization rules.

export default {
  async fetch(request, env, ctx) {
    // Assume JWT is already verified and we have the user's role
    // In a real app, this 'userRole' would come from the decoded JWT payload.
    const userRole = 'editor'; // Example role from a verified token

    if (request.url.includes('/admin') && userRole !== 'admin') {
      return new Response('Forbidden: Admins only!', { status: 403 });
    }

    if (request.method === 'POST' && userRole === 'guest') {
        return new Response('Forbidden: Guests cannot create!', { status: 403 });
    }

    return new Response(`Welcome, ${userRole}! Request processed.`, { status: 200 });
  },
};

Test Your Understanding

Which of the following statements correctly describe the difference between Authentication and Authorization?

Recap: AuthN & AuthZ

Great job! You've learned the fundamentals of securing your edge APIs.

  • Authentication confirms identity.
  • Authorization controls access.
  • API Keys offer simple authentication.
  • JWTs provide secure, self-contained authentication and can carry authorization claims.
  • RBAC (Role-Based Access Control) helps define permissions based on user roles.

These strategies are vital for building robust and secure edge applications.

자주 묻는 질문

“인증 및 권한 부여” 강의는 무료인가요?

네 — “인증 및 권한 부여” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Edge Computing with Cloudflare Workers & Deno 강의 전체를 잠금 해제할 수 있습니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 4개의 강의가 포함되어 있습니다.

“인증 및 권한 부여”에서 뭘 배우나요?

엣지 API 엔드포인트를 보호하기 위한 사용자 인증 및 권한 부여 전략을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Edge Computing with Cloudflare Workers & Deno을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Edge Computing with Cloudflare Workers & Deno을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Edge Computing with Cloudflare Workers & Deno은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“인증 및 권한 부여” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Edge Computing with Cloudflare Workers & Deno 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Edge Computing with Cloudflare Workers & Deno 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 인증 및 권한 부여
  2. 요청 빈도 제한 및 DDoS 보호
  3. 안전한 비밀 정보 관리
  4. 입력 정제 및 인젝션 방지
← Edge Computing with Cloudflare Workers & Deno(으)로 돌아가기