🔒 Security

Authorization

Authorization (Granting Access Permissions)

The process of checking whether an authenticated user has permission to access a specific resource. Answers the question "Is this user allowed to perform this action?" and has various access control models such as RBAC, ABAC, and ReBAC.

📖 Detailed Explanation

Authorization is a concept that, together with Authentication, forms a core pillar of security. While authentication verifies "Who are you?", authorization determines "What are you allowed to do?" For example, after logging in to a company system (authentication), accessing payroll data requires HR department permission (authorization). These two concepts are often confused, but they must be clearly distinguished in security design.

Authorization models have evolved with the complexity of systems. RBAC (Role-Based Access Control) grants permissions based on roles (e.g., admin, editor, viewer). ABAC (Attribute-Based Access Control) combines attributes of the user, the resource, and the environment to enable finer-grained control (e.g., "department=HR AND time=business hours"). ReBAC (Relationship-Based Access Control) is based on relationships between resources (e.g., "if you are the author of this document, you can edit it"). In modern systems, a hybrid approach is common, using RBAC as the base and fine-tuning with ABAC.

The Principle of Least Privilege is central to authorization design. Users should be granted only the minimum permissions necessary to perform their work. Excessive permissions increase the risk of insider threats, greater damage when an account is compromised, and compliance violations. In particular, permission management for AI agents and API keys should apply the principle of least privilege even more strictly.

In a Zero Trust architecture, authorization is continuous verification rather than a one-time event. Traditional models checked permissions once at login, but Zero Trust evaluates context (location, device, time, behavior patterns) on every request to determine permissions dynamically. PBAC (Policy-Based Access Control) is a modern approach that manages such complex authorization logic centrally and applies it consistently across APIs, services, and frontends.

💻 Code Example

// RBAC (Role-Based Access Control) 구현 예제 - Node.js
const express = require('express');
const app = express();

// 역할별 권한 정의
const PERMISSIONS = {
    admin: ['create', 'read', 'update', 'delete', 'manage_users'],
    editor: ['create', 'read', 'update'],
    viewer: ['read']
};

// 사용자-역할 매핑 (실제로는 DB에서 조회)
const USER_ROLES = {
    'user_001': ['admin'],
    'user_002': ['editor'],
    'user_003': ['viewer', 'editor']  // 복수 역할 가능
};

// 권한 확인 함수
function hasPermission(userId, requiredPermission) {
    const userRoles = USER_ROLES[userId] || [];
    return userRoles.some(role =>
        PERMISSIONS[role]?.includes(requiredPermission)
    );
}

// 인가 미들웨어
function authorize(requiredPermission) {
    return (req, res, next) => {
        const userId = req.user?.id;  // 인증 미들웨어에서 설정

        if (!userId) {
            return res.status(401).json({ error: 'Not authenticated' });
        }

        if (!hasPermission(userId, requiredPermission)) {
            return res.status(403).json({
                error: 'Forbidden',
                message: `Permission '${requiredPermission}' required`
            });
        }

        next();
    };
}

// 라우트에 인가 적용
app.get('/api/posts', authorize('read'), (req, res) => {
    res.json({ posts: ['post1', 'post2'] });
});

app.post('/api/posts', authorize('create'), (req, res) => {
    res.json({ message: 'Post created' });
});

app.delete('/api/posts/:id', authorize('delete'), (req, res) => {
    res.json({ message: 'Post deleted' });
});

app.delete('/api/users/:id', authorize('manage_users'), (req, res) => {
    res.json({ message: 'User deleted' });
});

// 403 vs 401 구분이 중요!
// 401 Unauthorized: 인증 안 됨 (누군지 모름)
// 403 Forbidden: 인증됨, 인가 안 됨 (권한 없음)
# ABAC (Attribute-Based Access Control) 구현 예제 - Python
from datetime import datetime
from typing import Dict, Any
from functools import wraps
from flask import request, jsonify, g

class ABACPolicy:
    """ABAC 정책 엔진"""

    def __init__(self):
        self.policies = []

    def add_policy(self, name: str, condition: callable, effect: str = "allow"):
        """정책 추가"""
        self.policies.append({
            "name": name,
            "condition": condition,
            "effect": effect
        })

    def evaluate(self, subject: Dict, resource: Dict, action: str, environment: Dict) -> bool:
        """정책 평가 - 모든 조건을 평가하여 접근 허용 여부 결정"""
        context = {
            "subject": subject,      # 사용자 속성 (역할, 부서, 직급 등)
            "resource": resource,    # 리소스 속성 (소유자, 민감도 등)
            "action": action,        # 수행할 작업
            "environment": environment  # 환경 속성 (시간, IP, 기기 등)
        }

        for policy in self.policies:
            if policy["condition"](context):
                return policy["effect"] == "allow"

        return False  # 기본: 거부 (Deny by default)


# ABAC 정책 정의
abac = ABACPolicy()

# 정책 1: 관리자는 모든 작업 허용
abac.add_policy(
    name="admin_full_access",
    condition=lambda ctx: ctx["subject"].get("role") == "admin",
    effect="allow"
)

# 정책 2: 업무 시간에만 민감한 데이터 접근 허용
abac.add_policy(
    name="sensitive_data_business_hours",
    condition=lambda ctx: (
        ctx["resource"].get("sensitivity") == "high" and
        9 <= ctx["environment"].get("hour", 0) <= 18 and
        ctx["subject"].get("department") == ctx["resource"].get("department")
    ),
    effect="allow"
)

# 정책 3: 리소스 소유자는 자신의 리소스에 모든 권한
abac.add_policy(
    name="owner_full_access",
    condition=lambda ctx: ctx["subject"].get("id") == ctx["resource"].get("owner_id"),
    effect="allow"
)

# 정책 4: 같은 부서원은 읽기 허용
abac.add_policy(
    name="department_read",
    condition=lambda ctx: (
        ctx["action"] == "read" and
        ctx["subject"].get("department") == ctx["resource"].get("department")
    ),
    effect="allow"
)


# Flask 인가 데코레이터
def abac_authorize(action: str, get_resource: callable):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            # 컨텍스트 수집
            subject = {
                "id": g.user.id,
                "role": g.user.role,
                "department": g.user.department
            }
            resource = get_resource(*args, **kwargs)
            environment = {
                "hour": datetime.now().hour,
                "ip": request.remote_addr,
                "user_agent": request.user_agent.string
            }

            # ABAC 평가
            if not abac.evaluate(subject, resource, action, environment):
                return jsonify({"error": "Forbidden"}), 403

            return f(*args, **kwargs)
        return wrapper
    return decorator


# 사용 예시
@app.route('/api/documents/', methods=['GET'])
@abac_authorize(action="read", get_resource=lambda doc_id: get_document(doc_id))
def get_document_api(doc_id):
    return jsonify(get_document(doc_id))
# OPA (Open Policy Agent) Rego 정책 예제
# 중앙화된 정책 관리로 마이크로서비스 전체에 일관된 인가 적용

package authz

import future.keywords.if
import future.keywords.in

# 기본: 접근 거부
default allow := false

# 관리자는 모든 접근 허용
allow if {
    input.user.role == "admin"
}

# RBAC: 역할 기반 권한 확인
allow if {
    # 사용자 역할에 해당하는 권한 조회
    permissions := role_permissions[input.user.role]
    # 요청한 액션이 권한 목록에 포함되어 있는지 확인
    input.action in permissions
}

role_permissions := {
    "editor": ["read", "create", "update"],
    "viewer": ["read"],
    "moderator": ["read", "update", "delete"]
}

# ABAC: 속성 기반 세부 제어
# 민감한 데이터는 같은 부서 + 업무 시간에만 접근
allow if {
    input.resource.sensitivity == "high"
    input.user.department == input.resource.department
    is_business_hours
}

is_business_hours if {
    hour := time.clock(time.now_ns())[0]
    hour >= 9
    hour <= 18
}

# ReBAC: 리소스 소유자는 모든 권한
allow if {
    input.user.id == input.resource.owner_id
}

# API 호출 예시 (curl)
# curl -X POST http://localhost:8181/v1/data/authz/allow \
#   -H "Content-Type: application/json" \
#   -d '{
#     "input": {
#       "user": {"id": "user_123", "role": "editor", "department": "engineering"},
#       "resource": {"id": "doc_456", "owner_id": "user_789", "department": "engineering", "sensitivity": "low"},
#       "action": "update"
#     }
#   }'
# 응답: {"result": true}

🗣️ Say It Like This in Practice

💬 In a Permission Design Meeting
"Let's start with basic RBAC, but add ABAC policies for access to sensitive data. For example, payroll information would be controlled by a compound condition: HR role + same department + business hours. If we centralize with OPA, we can apply consistent policies across all services."
💬 In a code review
"We need to distinguish between 401 and 403 in our responses. If the token is missing or expired, it's 401 Unauthorized; if the token is valid but the user lacks permission, it's 403 Forbidden. Right now the code responds with 401 for both, so the client can't tell whether it needs to log in again or request permission."
💬 In response to a security audit
"We've applied the principle of least privilege. All API keys and service accounts are granted only the permissions they need, and we conduct permission reviews every quarter. For departing employees, permission revocation is automated and immediate, and we can trace the full history of permission changes in the audit logs."

⚠️ Cautions & Best Practices

❌
Role Explosion

This is the phenomenon where roles multiply exponentially to achieve fine-grained control when using RBAC alone. When hundreds of roles like "engineering_viewer_project_a_readonly" appear, management becomes impossible. Use ABAC alongside it to control details through attributes.

❌
Hardcoded Permission Checks

If if (user.role === 'admin') is scattered throughout the code, you must modify all of it whenever the policy changes. Separate permission logic into centralized middleware or a policy engine.

❌
Permission Checks That Rely Only on the Frontend

Hiding buttons in the UI is not enough. Authorization checks must also be performed at the API level. Attackers can bypass UI controls using browser developer tools or direct API calls.

✅
Authorization Best Practices

Implement the principle of least privilege, audit logs for permission changes, regular permission reviews, immediate permission revocation for departing employees, minimized permissions for service accounts/API keys, and continuous verification based on Zero Trust. Separating policy from code with PBAC/OPA greatly improves maintainability.

🔗 Related Terms

📚 Learn More