[ NestJS ] Passport validate() 동작 안하는 문제 해결

jwkwon0817·2024년 8월 9일
0

Web Back-end

목록 보기
25/26
post-thumbnail

NestJS에서 passport를 사용하여 인증 시스템을 구현할
때, LocalStrategyJwtStrategy를 사용할 때 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() 함수가 정상적으로 동작하게 됩니다.

profile
SRIHS 119th SW

0개의 댓글