0Pricing
Node.js Backend Development Bootcamp · 강의

역할 기반 접근 제어(RBAC)

사용자 역할과 권한에 따라 특정 엔드포인트에 대한 접근을 제한하는 역할 기반 권한 부여를 구현합니다.

역할 기반 접근 제어(RBAC)은(는) CoddyKit의 무료 Node.js Backend Development Bootcamp 강의입니다. 이것은 6개 중 6번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Node.js Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Node.js Backend Development Bootcamp 강의에는 총 6개의 강의가 포함되어 있습니다.

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

What is RBAC?

Role-Based Access Control (RBAC) is a method of restricting access to resources based on the roles individual users have within an organization.

  • Instead of assigning permissions directly to users, permissions are assigned to roles.
  • Users are then assigned to roles, inheriting those permissions.
  • This simplifies security management, especially in larger applications.

Defining User Roles

First, we need to define the roles our application will use. These are typically broad categories like 'admin', 'editor', or 'basic_user'.

Using a Python Enum is a clean way to manage these roles:

from enum import Enum

class UserRole(str, Enum):
    ADMIN = "admin"
    EDITOR = "editor"
    BASIC_USER = "basic_user"

# Example usage:
# role = UserRole.ADMIN

User Role Assignment

Every user in your system will have one or more roles associated with them. In a real FastAPI application, this information usually comes from the user's authenticated token (e.g., a JWT payload).

For this lesson, we'll use a simple User model and a mock function to represent the currently authenticated user with their assigned roles.

from typing import List
from pydantic import BaseModel
from enum import Enum

class UserRole(str, Enum):
    ADMIN = "admin"
    EDITOR = "editor"
    BASIC_USER = "basic_user"

class User(BaseModel):
    username: str
    roles: List[UserRole]

# Mock function to get current user (normally from JWT)
async def get_current_user() -> User:
    # In a real app, this would decode a JWT
    # For demonstration, let's return a mock admin user
    return User(username="admin_user", roles=[UserRole.ADMIN])

Custom Role Dependency

FastAPI's dependency injection system is perfect for implementing RBAC. We can create a custom dependency that checks if the authenticated user has the necessary role(s) to access an endpoint.

  • This dependency will be reusable across many endpoints.
  • If the user doesn't have the required role, it raises an HTTPException.

Building the Role Checker

Our role_required dependency will take a list of roles. It will then fetch the current user and verify if any of their assigned roles match the required roles.

from fastapi import Depends, HTTPException, status
from typing import List
from pydantic import BaseModel
from enum import Enum

class UserRole(str, Enum):
    ADMIN = "admin"
    EDITOR = "editor"
    BASIC_USER = "basic_user"

class User(BaseModel):
    username: str
    roles: List[UserRole]

# Mock function to get current user
async def get_current_user() -> User:
    return User(username="test_user", roles=[UserRole.BASIC_USER])

def role_required(required_roles: List[UserRole]):
    async def role_checker(current_user: User = Depends(get_current_user)):
        if not any(role in current_user.roles for role in required_roles):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Not enough permissions"
            )
        return current_user
    return role_checker

Code: Admin-Only Endpoint

Here's a full FastAPI application demonstrating how to protect an endpoint so only users with the 'admin' role can access it. Run this code and try accessing /admin and /public.

from fastapi import FastAPI, Depends, HTTPException, status
from typing import List
from pydantic import BaseModel
from enum import Enum
import uvicorn

app = FastAPI()

class UserRole(str, Enum):
    ADMIN = "admin"
    EDITOR = "editor"
    BASIC_USER = "basic_user"

class User(BaseModel):
    username: str
    roles: List[UserRole]

# Mock function to get current user
# Change roles here to test different access levels
async def get_current_user() -> User:
    # Try changing to [UserRole.BASIC_USER] or [UserRole.ADMIN]
    return User(username="admin_user", roles=[UserRole.ADMIN])

def role_required(required_roles: List[UserRole]):
    async def role_checker(current_user: User = Depends(get_current_user)):
        if not any(role in current_user.roles for role in required_roles):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Not enough permissions"
            )
        return current_user
    return role_checker

@app.get("/public")
async def read_public_data():
    return {"message": "This is public data!"}

@app.get("/admin")
async def read_admin_data(current_user: User = Depends(role_required([UserRole.ADMIN]))):
    return {"message": f"Welcome, {current_user.username}! This is admin data."}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Testing the Role Check

When you run the previous code:

  • Access http://127.0.0.1:8000/public: This should always work.
  • Access http://127.0.0.1:8000/admin: This will work if get_current_user returns a user with UserRole.ADMIN.

Try changing the mock user's roles in get_current_user to [UserRole.BASIC_USER] and rerun the app. You'll see a 403 Forbidden error when trying to access /admin.

Allowing Multiple Roles

Sometimes, an endpoint should be accessible by more than one role. For example, both 'admin' and 'editor' users might be allowed to update an article.

Our role_required dependency is already designed for this! It accepts a List[UserRole], and the any() check means access is granted if the user has any one of the specified roles.

Code: Multiple Role Access

This example shows an endpoint accessible by either an 'admin' or an 'editor'. Try changing the mock user's roles to [UserRole.EDITOR] and [UserRole.BASIC_USER] to observe the access control.

from fastapi import FastAPI, Depends, HTTPException, status
from typing import List
from pydantic import BaseModel
from enum import Enum
import uvicorn

app = FastAPI()

class UserRole(str, Enum):
    ADMIN = "admin"
    EDITOR = "editor"
    BASIC_USER = "basic_user"

class User(BaseModel):
    username: str
    roles: List[UserRole]

# Mock function to get current user
# Change roles here to test different access levels
async def get_current_user() -> User:
    # Try [UserRole.ADMIN], [UserRole.EDITOR], or [UserRole.BASIC_USER]
    return User(username="editor_user", roles=[UserRole.EDITOR])

def role_required(required_roles: List[UserRole]):
    async def role_checker(current_user: User = Depends(get_current_user)):
        if not any(role in current_user.roles for role in required_roles):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Not enough permissions"
            )
        return current_user
    return role_checker

@app.get("/edit_content")
async def edit_content(current_user: User = Depends(role_required([UserRole.ADMIN, UserRole.EDITOR]))):
    return {"message": f"Hello {current_user.username}! You can edit content."}

@app.get("/view_only")
async def view_only_content(current_user: User = Depends(role_required([UserRole.BASIC_USER]))):
    return {"message": f"Hello {current_user.username}! You can view content."}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

RBAC Implementation Check

You need to create an endpoint /dashboard that should only be accessible by users with the ADMIN role. Which of the following is the correct way to apply the role_required dependency?

RBAC Recap

You've learned how to implement Role-Based Access Control in your FastAPI applications:

  • Defined roles using Python Enum for clarity.
  • Understood how user roles are typically associated (e.g., via JWTs).
  • Created a reusable custom dependency (role_required) to check user roles.
  • Applied this dependency to endpoints to restrict access based on single or multiple roles.

RBAC is a powerful way to manage permissions, making your API more secure and maintainable!

자주 묻는 질문

“역할 기반 접근 제어(RBAC)” 강의는 무료인가요?

네 — “역할 기반 접근 제어(RBAC)” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Node.js Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. Node.js Backend Development Bootcamp 강의에는 총 6개의 강의가 포함되어 있습니다.

“역할 기반 접근 제어(RBAC)”에서 뭘 배우나요?

사용자 역할과 권한에 따라 특정 엔드포인트에 대한 접근을 제한하는 역할 기반 권한 부여를 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Node.js Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Node.js Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

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

“역할 기반 접근 제어(RBAC)” 강의는 얼마나 걸리나요?

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

이 Node.js Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

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

이 강의의 모든 강의

  1. 사용자 등록과 로그인
  2. JWT 토큰 생성 및 검증
  3. 상태 비저장 인증을 위한 JWT
  4. OAuth2 비밀번호 흐름 연동
  5. 역할 기반 접근 제어
  6. 역할 기반 접근 제어(RBAC)
← Node.js Backend Development Bootcamp(으)로 돌아가기