🔒 Security

JWT

JSON Web Token

A self-contained token in JSON format with a Header.Payload.Signature structure. Enables stateless authentication without server sessions.

📖 Detailed Explanation

JWT (JSON Web Token) is an open standard defined in RFC 7519 that provides a way to securely transmit information between parties as a JSON object. "Self-contained" means that the token itself holds all the necessary information, so a user can be authenticated using only the token, without any separate database lookup. This makes a stateless architecture possible, in which no sessions are stored on the server.

A JWT consists of three parts: Header, Payload, and Signature, and the parts are separated by dots (.). The Header specifies the token type (JWT) and the signing algorithm (e.g., HS256, RS256). The Payload carries claims, which include registered claims (iss, sub, exp, etc.) and custom claims. The Signature is a value obtained by signing the Header and Payload with a secret key, and it prevents token tampering.

HS256 (HMAC-SHA256) is a symmetric-key method that uses the same secret key for signing and verification. It is simple, but the key must be shared securely, so it suits a single service. RS256 (RSA-SHA256) is an asymmetric-key method that signs with a private key and verifies with a public key. In a microservices environment, only the authentication server holds the private key while the other services can verify with the public key, which makes it scalable.

The Access Token and Refresh Token pattern is common. An Access Token has a short lifetime (15 minutes to 1 hour) and is used for API requests. A Refresh Token has a long lifetime (7 to 30 days) and is used to obtain a new Access Token. Even if an Access Token is stolen, the short lifetime minimizes the damage, and applying Refresh Token Rotation strengthens security further.

💻 Code Example

# JWT 생성 및 검증 - Python PyJWT 라이브러리
import jwt
from datetime import datetime, timedelta
from typing import Optional
import secrets

class JWTManager:
    """JWT 토큰 관리 클래스"""

    def __init__(self, secret_key: str = None, algorithm: str = "HS256"):
        self.secret_key = secret_key or secrets.token_hex(32)
        self.algorithm = algorithm
        self.access_token_expire = timedelta(minutes=30)
        self.refresh_token_expire = timedelta(days=7)

    def create_access_token(self, user_id: str, roles: list = None) -> str:
        """Access Token 생성"""
        payload = {
            "sub": user_id,           # Subject (사용자 ID)
            "roles": roles or [],     # 사용자 역할
            "type": "access",
            "iat": datetime.utcnow(), # Issued At (발급 시간)
            "exp": datetime.utcnow() + self.access_token_expire  # 만료 시간
        }
        return jwt.encode(payload, self.secret_key, algorithm=self.algorithm)

    def create_refresh_token(self, user_id: str) -> str:
        """Refresh Token 생성"""
        payload = {
            "sub": user_id,
            "type": "refresh",
            "iat": datetime.utcnow(),
            "exp": datetime.utcnow() + self.refresh_token_expire,
            "jti": secrets.token_hex(16)  # 고유 토큰 ID (revocation용)
        }
        return jwt.encode(payload, self.secret_key, algorithm=self.algorithm)

    def verify_token(self, token: str) -> Optional[dict]:
        """토큰 검증 및 페이로드 반환"""
        try:
            payload = jwt.decode(
                token,
                self.secret_key,
                algorithms=[self.algorithm]
            )
            return payload
        except jwt.ExpiredSignatureError:
            print("토큰이 만료되었습니다")
            return None
        except jwt.InvalidTokenError as e:
            print(f"유효하지 않은 토큰: {e}")
            return None

    def refresh_access_token(self, refresh_token: str) -> Optional[str]:
        """Refresh Token으로 새 Access Token 발급"""
        payload = self.verify_token(refresh_token)

        if not payload:
            return None

        if payload.get("type") != "refresh":
            print("Refresh Token이 아닙니다")
            return None

        # 새 Access Token 발급
        return self.create_access_token(payload["sub"])


# 사용 예시
if __name__ == "__main__":
    jwt_manager = JWTManager()

    # 1. 로그인 시: 토큰 쌍 발급
    user_id = "user_12345"
    access_token = jwt_manager.create_access_token(user_id, ["user", "admin"])
    refresh_token = jwt_manager.create_refresh_token(user_id)

    print(f"Access Token: {access_token[:50]}...")
    print(f"Refresh Token: {refresh_token[:50]}...")

    # 2. API 요청 시: Access Token 검증
    payload = jwt_manager.verify_token(access_token)
    if payload:
        print(f"인증된 사용자: {payload['sub']}, 역할: {payload['roles']}")

    # 3. Access Token 만료 시: Refresh Token으로 갱신
    new_access_token = jwt_manager.refresh_access_token(refresh_token)
    print(f"새 Access Token: {new_access_token[:50]}...")
// JWT 생성 및 검증 - Node.js jsonwebtoken
const jwt = require('jsonwebtoken');
const crypto = require('crypto');

class JWTManager {
    constructor(secretKey = null) {
        this.secretKey = secretKey || crypto.randomBytes(32).toString('hex');
        this.accessTokenExpire = '30m';  // 30분
        this.refreshTokenExpire = '7d';  // 7일
    }

    // Access Token 생성
    createAccessToken(userId, roles = []) {
        return jwt.sign(
            {
                sub: userId,
                roles: roles,
                type: 'access'
            },
            this.secretKey,
            {
                algorithm: 'HS256',
                expiresIn: this.accessTokenExpire
            }
        );
    }

    // Refresh Token 생성
    createRefreshToken(userId) {
        return jwt.sign(
            {
                sub: userId,
                type: 'refresh',
                jti: crypto.randomBytes(16).toString('hex')
            },
            this.secretKey,
            {
                algorithm: 'HS256',
                expiresIn: this.refreshTokenExpire
            }
        );
    }

    // 토큰 검증
    verifyToken(token) {
        try {
            return jwt.verify(token, this.secretKey);
        } catch (error) {
            if (error.name === 'TokenExpiredError') {
                console.log('토큰이 만료되었습니다');
            } else {
                console.log(`유효하지 않은 토큰: ${error.message}`);
            }
            return null;
        }
    }

    // 토큰에서 페이로드 추출 (검증 없이)
    decode(token) {
        return jwt.decode(token, { complete: true });
    }
}

// Express 미들웨어 예시
const authMiddleware = (jwtManager) => {
    return (req, res, next) => {
        const authHeader = req.headers.authorization;

        if (!authHeader || !authHeader.startsWith('Bearer ')) {
            return res.status(401).json({ error: 'No token provided' });
        }

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

        if (!payload) {
            return res.status(401).json({ error: 'Invalid token' });
        }

        req.user = payload;
        next();
    };
};

// 사용 예시
const jwtManager = new JWTManager();

// 로그인 API
const login = (userId, roles) => {
    return {
        accessToken: jwtManager.createAccessToken(userId, roles),
        refreshToken: jwtManager.createRefreshToken(userId),
        expiresIn: 1800 // 30분 (초)
    };
};

// 토큰 갱신 API
const refreshTokens = (refreshToken) => {
    const payload = jwtManager.verifyToken(refreshToken);

    if (!payload || payload.type !== 'refresh') {
        throw new Error('Invalid refresh token');
    }

    return {
        accessToken: jwtManager.createAccessToken(payload.sub),
        // Refresh Token Rotation: 새 Refresh Token도 발급
        refreshToken: jwtManager.createRefreshToken(payload.sub)
    };
};

console.log(login('user123', ['admin']));
JWT 구조 분석
==============

JWT 형식: xxxxx.yyyyy.zzzzz
          Header.Payload.Signature


1. Header (헤더) - Base64Url 인코딩
====================================
{
  "alg": "HS256",    // 서명 알고리즘
  "typ": "JWT"       // 토큰 타입
}

인코딩: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9


2. Payload (페이로드) - Base64Url 인코딩
========================================
{
  // 등록된 클레임 (Registered Claims)
  "iss": "https://api.example.com",  // 발급자
  "sub": "user_12345",               // 주제 (사용자 ID)
  "aud": "https://app.example.com",  // 대상자
  "exp": 1735689600,                 // 만료 시간 (Unix timestamp)
  "nbf": 1735686000,                 // 유효 시작 시간
  "iat": 1735686000,                 // 발급 시간
  "jti": "unique-token-id-123",      // JWT ID (고유 식별자)

  // 사용자 정의 클레임
  "roles": ["user", "admin"],
  "permissions": ["read", "write"]
}


3. Signature (서명)
====================
HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)


완성된 JWT 예시
================
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiJ1c2VyXzEyMzQ1IiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c


알고리즘 선택 가이드
====================
HS256 (HMAC + SHA-256)
- 대칭키: 같은 키로 서명/검증
- 단일 서비스, 간단한 구조에 적합
- 키 공유 필요

RS256 (RSA + SHA-256)
- 비대칭키: 개인키 서명, 공개키 검증
- 마이크로서비스, 외부 연동에 적합
- 인증 서버만 개인키 보유

ES256 (ECDSA + SHA-256)
- 비대칭키: 더 짧은 키 길이로 동등 보안
- 모바일/IoT 환경에 적합

🗣️ Say It Like This in Practice

💬 In an Authentication System Design Meeting
"We set the Access Token to 15 minutes and the Refresh Token to 7 days, and we apply Refresh Token Rotation so that a new Refresh Token is issued every time we renew. If we detect reuse of a stolen Refresh Token, we invalidate all of that user's sessions."
💬 In a security review
"A JWT is Base64-encoded, not encrypted. You must not put sensitive information in the Payload. Never include things like passwords or credit card numbers. If necessary, you should encrypt the payload using JWE (JSON Web Encryption)."
💬 In a Microservices Architecture Discussion
"If the authentication server issues JWTs with RS256, each microservice can verify tokens with only the public key. Distributed verification is possible without sharing a secret key, so it scales well. If you provide the public key through a JWKS endpoint, key rotation is also easy."

⚠️ Cautions & Best Practices

❌
Do Not Store Sensitive Information in the Payload

A JWT Payload is merely Base64-encoded, not encrypted. Anyone can decode it and view the contents, so do not include passwords, personal information, etc.

❌
The alg: "none" Vulnerability

Setting the signing algorithm to "none" bypasses signature verification. Explicitly specify a list of allowed algorithms in the library.

❌
Long Expiration Time

If you set an Access Token's lifetime too long (e.g., 1 year), it can be abused for a long time if stolen. 15 minutes to 1 hour is recommended, and renew with a Refresh Token.

✅
JWT Best Practices

Short Access Token lifetime + Refresh Token Rotation, use RS256 or ES256, minimize the Payload, mandatory verification of the expiration time (exp), and support immediate invalidation with a blacklist.

🔗 Related Terms

📚 Learn More