Community코딩 & 개발github.com

mindrally/jwt-security

JWT 인증 구현 가이드: 토큰 생성, 검증 및 저장에 대한 보안 모범 사례

jwt-security란 무엇인가요?

이 스킬은 JWT(JSON Web Token) 기반 인증 시스템을 구현할 때 따라야 할 보안 모범 사례를 제공합니다. 토큰 생성 시 강력한 서명 알고리즘(예: HS256 또는 RS256) 선택, 만료 시간 설정, 클레임 검증 등 안전한 토큰 발급 방법을 안내합니다. 또한 토큰 검증 단계에서는 서명 확인, 만료 시간 확인, 발급자(iss) 및 대상자(aud) 검증 등 필수 검증 과정을 다룹니다. 토큰 저장 측면에서는 클라이언트 측의 안전한 저장소(예: HttpOnly 쿠키) 사용과 XSS 공격 방지 등 실제 배포 환경에서 고려해야 할 핵심 보안 사항을 포함합니다. 이 스킬은 Claude Code, Cursor, Codex 등 다양한 AI 에이전트 플랫폼에서 활용할 수 있으며, 개발자가 JWT 보안 취약점을 사전에 방지하고 안전한 인증 파이프라인을 구축하도록 돕습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mindrally/skills/tree/main/skills/jwt-security

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

jwt-security은(는) 무엇을 하나요?

JWT 인증 구현 가이드: 토큰 생성, 검증 및 저장에 대한 보안 모범 사례

개요

이 스킬은 JWT(JSON Web Token) 기반 인증 시스템을 안전하게 구현하기 위한 지침을 제공합니다. 다음 영역을 다룹니다:

  • 토큰 생성: 서명 알고리즘, 만료, 클레임 설정
  • 토큰 검증: 서명, 만료, 발급자, 대상자 검증
  • 토큰 저장: 클라이언트 측 안전한 저장소 및 XSS 방지

보안 원칙

1. 강력한 서명 알고리즘 사용

  • HS256(HMAC with SHA-256) 또는 RS256(RSA with SHA-256) 사용
  • none 알고리즘 절대 사용 금지
  • 약한 알고리즘(예: HS256을 none으로 다운그레이드) 방지

2. 짧은 만료 시간 설정

{
  "exp": 1710000000,
  "iat": 1709996400
}
  • 만료 시간(exp)을 15분 이내로 설정
  • 갱신 토큰을 사용하여 재인증

3. 필수 클레임 검증

클레임설명필수 여부
iss발급자예
sub주제 (사용자 ID)예
aud대상자예
exp만료 시간예
iat발급 시간예
jtiJWT ID (중복 방지)권장

4. 안전한 저장소

  • HttpOnly 쿠키: Secure, SameSite=Strict 속성과 함께 사용
  • 로컬 스토리지 지양: XSS 공격에 취약하므로 사용하지 않음

구현 예제

Node.js (jsonwebtoken 라이브러리)

const jwt = require('jsonwebtoken');

// 토큰 생성
const token = jwt.sign(
  { sub: 'user123', role: 'admin' },
  process.env.JWT_SECRET,
  { algorithm: 'HS256', expiresIn: '15m', issuer: 'myapp' }
);

// 토큰 검증
try {
  const decoded = jwt.verify(token, process.env.JWT_SECRET, {
    algorithms: ['HS256'],
    issuer: 'myapp'
  });
  console.log('유효한 토큰:', decoded);
} catch (err) {
  console.error('토큰 검증 실패:', err.message);
}

Python (PyJWT 라이브러리)

import jwt
from datetime import datetime, timedelta

# 토큰 생성
payload = {
    'sub': 'user123',
    'role': 'admin',
    'exp': datetime.utcnow() + timedelta(minutes=15),
    'iss': 'myapp'
}
token = jwt.encode(payload, 'your-secret-key', algorithm='HS256')

# 토큰 검증
try:
    decoded = jwt.decode(token, 'your-secret-key', algorithms=['HS256'], issuer='myapp')
    print('유효한 토큰:', decoded)
except jwt.ExpiredSignatureError:
    print('토큰이 만료되었습니다.')
except jwt.InvalidTokenError as e:
    print('잘못된 토큰:', str(e))

환경 변수

변수명설명예시
JWT_SECRETHS256 서명에 사용되는 비밀 키your-256-bit-secret
JWT_ISSUER토큰 발급자 식별자https://api.example.com
JWT_AUDIENCE대상 애플리케이션https://app.example.com
JWT_EXPIRY토큰 만료 시간 (분)15

주의 사항

  1. 비밀 키를 코드에 하드코딩하지 마세요. 환경 변수나 비밀 관리 서비스를 사용하세요.
  2. 토큰 블랙리스트를 구현하세요. 로그아웃 시 토큰을 무효화합니다.
  3. HTTPS를 사용하세요. 전송 중 토큰을 암호화합니다.
  4. 페이로드에 민감한 정보를 포함하지 마세요. JWT는 서명만 되고 암호화되지 않습니다.

참고 자료

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

mindrally/accessibility-a11y

Implement web accessibility (a11y) best practices following WCAG guidelines to create inclusive, accessible user interfaces.

mindrally/chrome-extension-development

Expert guidelines for Chrome extension development with Manifest V3, covering security, performance, and best practices. Use when building browser extensions, creating popup UIs, implementing content scripts, working with Chrome APIs, managing extension permissions, or publishing to Chrome Web Store.

mindrally/computer-vision-opencv

Expert guidance for computer vision development using OpenCV, PyTorch, and modern deep learning techniques for image and video processing.

mindrally/data-analysis-jupyter

Expert guidance for data analysis, visualization, and Jupyter Notebook development with pandas, matplotlib, seaborn, and numpy.

mindrally/deep-learning-pytorch

Expert guidance for deep learning, transformers, diffusion models, and LLM development with PyTorch, Transformers, Diffusers, and Gradio.

mindrally/expo-react-native-typescript

Expert in Expo React Native TypeScript mobile development with best practices

mindrally/fastapi-python

Expert in FastAPI Python development with best practices for APIs and async operations

mindrally/framer-motion

Expert guidelines for building performant animations with Framer Motion/Motion library in React applications

mindrally/htmx

HTMX development guidelines for building dynamic web applications with minimal JavaScript using HTML attributes.

mindrally/machine-learning

Machine learning development with JAX, functional programming patterns, and high-performance computing.

mindrally/mysql-best-practices

MySQL development best practices for schema design, query optimization, and database administration

mindrally/nextjs-react-typescript

Expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI and Tailwind

mindrally/nextjs-typescript-tailwindcss-supabase

Full-stack Next.js 14 development with TypeScript, TailwindCSS, and Supabase for building production-ready web applications.

mindrally/odoo-development

Expert guidance for Odoo ERP development including Python ORM, XML views, and module architecture

mindrally/puppeteer-automation

Expert guidance for browser automation using Puppeteer with best practices for web scraping, testing, screenshot capture, and JavaScript execution in headless Chrome.

mindrally/redis-best-practices

Redis development best practices for caching, data structures, and high-performance key-value operations

mindrally/scrapy-web-scraping

Expert guidance for building web scrapers and crawlers using the Scrapy Python framework with best practices for spider development, data extraction, and pipeline management.

mindrally/scss-best-practices

SCSS/Sassy CSS best practices and coding guidelines for maintainable, scalable stylesheets

mindrally/typeorm

Guidelines for developing with TypeORM, a full-featured ORM for TypeScript and JavaScript supporting multiple databases

mindrally/web-scraping

Expert in web scraping and data extraction with Python tools

관련 스킬