목차
개요
JWT 인증 에러시 메세지가 "Unauthorized"로 통일 되서 나오는게 싫었다.
스택오버플로우 참고, AuthGuard의 handleRequest 메서드를 사용하여 에러 메세지를 변경하였다.
아래 예제에는 토큰 만료 에러만 분기 처리를 했지만 그 외의 상황도 추가할 예정이다.
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { TokenExpiredError } from 'jsonwebtoken';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
handleRequest(err: any, user: any, info: any, context: any, status: any) {
if (info instanceof TokenExpiredError) {
throw new UnauthorizedException('유효 시간이 만료된 토큰 입니다.');
}
return super.handleRequest(err, user, info, context, status);
}
}
'개발 공부 > NestJS' 카테고리의 다른 글
Multer를 사용해 ImgBB에 이미지 올리기 (0) | 2023.04.05 |
---|---|
인 메모리 데이터베이스, Redis (2편) (0) | 2023.03.26 |
인 메모리 데이터베이스, Redis (1편) (0) | 2023.03.26 |
Serialize 직렬화 (0) | 2023.03.23 |
인터셉터 Interceptor (0) | 2023.03.19 |
개요
JWT 인증 에러시 메세지가 "Unauthorized"로 통일 되서 나오는게 싫었다.
스택오버플로우 참고, AuthGuard의 handleRequest 메서드를 사용하여 에러 메세지를 변경하였다.
아래 예제에는 토큰 만료 에러만 분기 처리를 했지만 그 외의 상황도 추가할 예정이다.
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { TokenExpiredError } from 'jsonwebtoken';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
handleRequest(err: any, user: any, info: any, context: any, status: any) {
if (info instanceof TokenExpiredError) {
throw new UnauthorizedException('유효 시간이 만료된 토큰 입니다.');
}
return super.handleRequest(err, user, info, context, status);
}
}
'개발 공부 > NestJS' 카테고리의 다른 글
Multer를 사용해 ImgBB에 이미지 올리기 (0) | 2023.04.05 |
---|---|
인 메모리 데이터베이스, Redis (2편) (0) | 2023.03.26 |
인 메모리 데이터베이스, Redis (1편) (0) | 2023.03.26 |
Serialize 직렬화 (0) | 2023.03.23 |
인터셉터 Interceptor (0) | 2023.03.19 |