jwtVerification
JWT(JSON Web Token) 인증 미들웨어입니다. Express 라우트에 적용하여 Bearer 토큰을 검증합니다.
Import
import { jwtVerification } from '@asapjs/router';
시그니처
const jwtVerification = (auth?: boolean) =>
(req: Request, res: Response, next: NextFunction) => void
파라미터
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
auth | boolean | false | true: 토큰 필수 (없으면 403). false: 토큰 선택적 (있으면 디코드, 없어도 통과) |
동작
Authorization헤더에서Bearer <token>추출getConfig().auth.jwt_access_token_secret으로 토큰 검증- 검증 성공 →
req.user에 디코딩된 페이로드 저장 - 검증 실패:
auth=true+ 토큰 없음 →403 NO Token Providedauth=true+ invalid signature →403auth=true+ 만료 등 →401 Unauthorizedauth=false→ 다음 미들웨어로 통과
사용 예제
인증 필수 라우트
import { jwtVerification } from '@asapjs/router';
// 미들웨어로 적용
router.get('/profile', jwtVerification(true), (req, res) => {
// req.user에 디코딩된 JWT 페이로드
res.json({ user: req.user });
});
인증 선택적 라우트
// 토큰이 있으면 req.user 설정, 없어도 에러 없이 통과
router.get('/posts', jwtVerification(false), (req, res) => {
if (req.user) {
// 로그인 사용자
} else {
// 비로그인 사용자
}
});
설정 (config)
{
"auth": {
"jwt_access_token_secret": "your-secret-key"
}
}
관련 API
- RouterModule — 서버 모듈
- HttpException — HTTP 에러 처리
- authorization — 권한 관련 문서