NestJS에서 passport를 사용하여 인증 시스템을 구현할 때, LocalStrategy
와 JwtStrategy
를 사용할 때 validate()
가 동작하지 않아 인증 시스템이 제대로 동작하지 않는 문제가 발생하는 경우가 있다.
공식 문서에는 나와있지 않는 부분에 아래 코드를 채워줘야한다.
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super();
}
async validate(email: string, password: string): Promise<any> {
const user = await this.authService.validateUser(email, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
이러한 코드에서 생성자의 super() 부분에 필드를 작성해줘야한다.
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({
usernameField: 'email',
passwordField: 'password',
});
}
async validate(email: string, password: string): Promise<any> {
const user = await this.authService.validateUser(email, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
이렇게 적으면 validate()
함수가 정상적으로 동작하게 된다.