@jeonghochoi/jwt
v0.1.2
Published
NestJS JWT module
Readme
@jeonghochoi/jwt-core
NestJS JWT Authentication Core Library
NestJS 애플리케이션에서 JWT 인증을 의미 있는 Guard / Decorator 형태로 사용하기 위한 Core 라이브러리
✨ Features
- JWT 인증 필수 / 선택 정책 분리
- Passport 기반 NestJS 표준 인증 파이프라인
- 의미 중심 Guard (
MandatoryJwtAuthGuard,JwtContextGuard) - 가독성 높은 Decorator (
@JwtRequired()) - RBAC Guard와 자연스럽게 결합 가능
- 앱에서 secret / 만료 정책 주입 (env 직접 접근 ❌)
📦 Installation
npm install @jeonghochoi/jwt-core
# or
pnpm add @jeonghochoi/jwt-core⚙️ Peer Dependencies
이 라이브러리는 NestJS 확장 라이브러리이므로
아래 패키지들은 사용자 앱에서 직접 설치되어 있어야 합니다.
{
"@nestjs/common": "^10 || ^11",
"@nestjs/jwt": "^10 || ^11",
"@nestjs/passport": "^10 || ^11",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1"
}🚀 Quick Start
1️⃣ Module 등록
import { Module } from '@nestjs/common';
import { JwtCoreModule } from '@jeonghochoi/jwt-core';
@Module({
imports: [
JwtCoreModule.register({
secret: process.env.JWT_SECRET!,
signOptions: {
expiresIn: '1h',
},
}),
],
})
export class AppModule {}🔐 JWT 필수 API
import { Controller, Get, Req } from '@nestjs/common';
import { JwtRequired } from '@jeonghochoi/jwt-core';
@Controller('/me')
export class MeController {
@JwtRequired()
@Get()
getMe(@Req() req: any) {
return req.user;
}
}- JWT 없음 →
401 Unauthorized - JWT 있음 →
req.user에 payload 주입
🔓 JWT 선택 API (Guest + User)
JwtContextGuard 사용
import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import { JwtContextGuard } from '@jeonghochoi/jwt-core';
@Controller('/articles')
@UseGuards(JwtContextGuard)
export class ArticleController {
@Get()
list(@Req() req: any) {
return {
user: req.user ?? null,
};
}
}- JWT 없음 → guest
- JWT 있음 →
req.user채워짐 - 절대 요청을 차단하지 않음
🧠 Guard 설계 철학
Guard 역할 분리
Request
├─ JwtContextGuard (optional / enrich)
├─ MandatoryJwtAuthGuard (authentication)
└─ RBAC Guard (authorization)| Guard | 역할 | | --------------------- | ----------------------- | | JwtContextGuard | JWT 있으면 context 채움 | | MandatoryJwtAuthGuard | JWT 없으면 차단 | | RBAC Guard | 권한 판단 |
🧩 Decorators
@JwtRequired()
JWT 인증이 반드시 필요한 API에 사용합니다.
@JwtRequired()
@Get('/protected')
protectedApi() {}- 내부적으로
MandatoryJwtAuthGuard를 사용 - Guard 구현 세부사항을 숨김
🔗 RBAC와 함께 사용 예시
@JwtRequired()
@RequirePermission('order.create')
@Post('/orders')
createOrder() {}인증 → 인가 순서가 코드에서 자연스럽게 드러납니다.
🧪 Testing Checklist
- Nest 앱 정상 기동
- JWT 없는 protected API → 401
- JWT 있는 protected API → 200
- Optional API에서 guest/user 구분
- RBAC Guard와 충돌 없음
❗ Notes
- 이 라이브러리는 JWT payload 구조를 해석하지 않습니다
- payload 의미 해석은 애플리케이션 책임입니다
process.env접근은 라이브러리 내부에서 하지 않습니다
📄 License
MIT
