인프런 커뮤니티 질문&답변

61250님의 프로필 이미지

작성한 질문수

탄탄한 백엔드 NestJS, 기초부터 심화까지

passport와 인증 전략 & Custom decorator

JwtAuthGuard가 Strategy를 어떻게 알고 실행하는건가요?

해결된 질문

21.08.15 17:15 작성

·

758

3

import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

AuthGuard를 상속받으니 해당 클래스 내에서 Strategy를 찾아서 validate 함수를 실행하는 것 같긴 한데

jwt.guard에는 인자로 직접 의존성을 주입하지 않고도

jwt.strategy의 클래스를 어떻게 찾아내는지 잘 모르겠습니다.

답변 1

5

윤상석님의 프로필 이미지
윤상석
지식공유자

2021. 08. 15. 19:56

안녕하세요!

관련 코드를 보여드리고 답변 진행하겠습니다.

"auth.module.ts"

import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt/jwt.strategy';


@Module({
imports: [
...
PassportModule.register({ defaultStrategy: 'jwt', session: false }),
...
],
providers: [JwtStrategy, ...],

})
export class AuthModule {}

"jwt.guard.ts"

import { AuthGuard } from '@nestjs/passport';
...

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

"jwt.strategy.ts"

import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
...

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
...
}

@UseGuard(JwtAuthGuard)로 데코레이팅된 컨트롤러가 실행되면 JwtAuthGuard는 자동으로 PassportStrategy를 상속받은 JwtStrategy를 찾아서 로직을 수행합니다.

여기서 JwtAuthGuard가 JwtStrategy를 찾을 수 있는 이유는 JwtStrategy는 AuthModule의 프로바이더로 등록이 되어 있고 "@nestjs/passport"의 내부 로직에 의해 PassportStrategy를 상속받은 전략 클래스(JwtStrategy)를 자동으로 찾아냅니다.

JwtAuthGuard는 AuthGuard("jwt") 즉, jwt 유형의 AuthGuard를 상속받은 클래스이기 때문에 PassportStrategy를 상속받은 여러가지 클래스 중에서(예를들어 로그인, 인증 방식에 따라 LocalStrategy, KakaoStrategy 등 여러가지로 정의될 수 있습니다.) passport-jwt의 Strategy를 인자로 받은 PassportStrategy를 상속받은 JwtStrategy을 찾는 것 입니다.

결론적으로 if (@UseGuard(JwtAuthGuard)로 데코레이팅된 컨트롤러가 실행)

1. JwtAuthGuard는 PassportStrategy를 상속받은 전략 클래스인 JwtStrategy를 찾는다. ("@nestjs/passport" 로직에 의해)

(단, 프로바이더에 등록 되어 있어야 합니다.)

2. JwtStrategy의 로직이 수행.

추가적으로 궁금하신 것 있으시면 답글 남겨주세요.

감사합니다. :)

61250님의 프로필 이미지
61250
질문자

2021. 08. 15. 20:23

passport-jwt 의 Strategy를 인자로 받았기 때문에 'jwt'로 인식하는거군요 감사합니다! 

61250님의 프로필 이미지

작성한 질문수

질문하기