package
"passport": "^0.6.0",
"passport-jwt": "^4.0.0",
"@nestjs/passport": "^9.0.0",
"@nestjs/jwt": "^9.0.0",
"@types/passport-jwt": "^3.0.6",
module
auth.module.ts
JWT는 Json-web-token의 약자이다. 즉, json 포멧을 사용하여 사용자 인증과 관련된 데이터를 담고 있는 웹 기반 토큰이다.
구조는 Header, payload, signature로 구성되어있고 각각은 다음 내용을 가지고 있다.
header: base64에 기반하여 인코딩 타입과 알고리즘
payload: base64에 기반하여 인코딩된 데이터
signature: header/payload를 조합하여 secret Key로 이를 서명한 것을 base64에 기반하여 인코딩
auth.module.ts
imports: [JwtModule.register({
// jwt 토큰 생성용 모듈, 이게 있어야 jwtService를 의존성 주입 가능
secret: process.env.secretKey,
signOptions: { expiresIn: '60s' }, // 만료기간
}),]
@Injectable()
export class AuthService {
constructor(private readonly catsRepository: CatsRepository, private jwtService: JwtService) {} // 로그인 시 request로 받아온 것이 모든 유효성 검증을 마쳤을 때에 유효성 검증이 들어가야하므로, catsrepository를 의존성 주입
async jwtLogIn(data: LoginRequestDto) {
const { email, password } = data;
const cat = await this.catsRepository.existsByEmail(email);
if (!cat) {
throw new UnauthorizedException('이메일과 비밀번호를 확인해주세요');
}
const isPasswordValidated: boolean = await bcrypt.compare(password, cat.data.password);
if (!isPasswordValidated) {
throw new UnauthorizedException('이메일과 비밀번호를 확인해주세요');
}
const payload = { email };
return {
token: this.jwtService.sign(payload),
};
}
}