NestJS에서 JWT토큰을 이용한 인증신에는 Guard를 사용한다.
Guard는 라우팅 전에 작동하는 일종의 미들웨어이다.
사용할 패키지: passport
npm install --save @nestjs/passport @types/passport-jwt

위의 사진처럼 클라이언트가 createApply라는 함수가 있다고 하자
createApply는 로그인 상태여야 하는데 함수위에 UserGuards데코레이터 안에 Guard모듈을 가져와서 넣어주면 된다.

import {
CanActivate,
ExecutionContext,
HttpException,
HttpStatus,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { Request } from 'express'
export class Guard implements CanActivate

private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.cookies.authorization.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
cookies안에 authorization이라는 bearer타입의 토큰을
split으로 나눈뒤 token값을 반환한다.
const token = this.extractTokenFromHeader(request); // Request의 token을 가지고 온다
if (!token) {
// 토큰이 없으면 에러처리
throw new UnauthorizedException();
}
try {
const payload = await this.jwtService.verifyAsync(token, {
secret: this.configService.get<string>('ACCESS_TOKEN_KEY'),
});
// 💡 We're assigning the payload to the request object here
// so that we can access it in our route handlers
request['user'] = payload;
} catch {
throw new UnauthorizedException();
}
return true;