inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

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

passport와 인증 전략 & Custom decorator

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

해결된 질문

900

61250

작성한 질문수 2

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의 클래스를 어떻게 찾아내는지 잘 모르겠습니다.

nodejs mongodb express ssr NestJS

답변 1

5

윤상석

안녕하세요!

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

"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의 로직이 수행.

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

감사합니다. :)

0

61250

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

프로젝트 환경 세팅할 때 최신 노드 버젼을 사용하시는 분들은 참고하셔도 좋을 것 같아요~

2

83

1

DTO에 대한 질문

1

88

2

백엔드 MVC에서 View의 역할은 무엇인가요?

1

95

2

추가 업데이트 관련 건

0

92

2

nest js 버전문제

0

81

2

mongdb 스키마 공식 문서와 형태가 다른 이유 궁금합니다.

0

103

1

라인 끝에 에러 표시(eslint) 때문에 구글 찾아 보니.

0

77

1

전체 고양이 조회 라우터 중 error.message 오류

0

70

1

캡슐화 추가 설명 중 단일책임원칙 관련 질문

0

106

0

42강 고양이끼리 소통 댓글 구현 중 Schema hasn't been registered for model 'comments' 에러 해결

0

82

1

채팅 이슈

0

134

1

모듈이 더 이상 지원하지 않는답니다

0

207

1

오류가 있습니다

0

107

1

import 에서 오류가 납니다

0

128

1

이런 오류가 나옵니다

0

101

1

에러가 발생합니다

0

111

1

프론트 에러 뜨는데 수정 안해주시나요

0

159

1

emit() broadcast.emit() 질문있습니다

0

103

1

서버연결이 안됩니다.

1

403

1

[PM2][ERROR] Command not found

0

521

1

S3에 업로드까지는 성공했는데 사진이 나오지 않습니다.

0

248

1

error_code : Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.ts(2339)

0

603

1

jwt를 따로 연습하고 있는데 env를 못읽는 것 같습니다.

0

324

2

Ec2로 안하시는 이유가 있을까요?

0

343

1