본문 바로가기

Nodejs/NestJS

[NestJS] passport-jwt JWTStrategy 10

yarn add @nestjs/passport passport passport-jwt jsonwebtoken @types/jsonwebtoken

 

jwtStragety 추가하고

Guard 추가한 후, 적용할 controller나 method에 guard 적용

import { FastifyRequest } from "fastify";
import { PassportStrategy } from "@nestjs/passport";
import { Injectable } from "@nestjs/common";
import { Strategy as JwtStrategy, ExtractJwt, VerifiedCallback } from "passport-jwt";
import { ConfigService } from "@nestjs/config";

@Injectable()
export class UserTokenStrategy extends PassportStrategy(JwtStrategy, "user:token") {
  constructor(configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: configService.get("SESSION_SECRET"),
      ignoreExpiration: false,
    });
  }

  async validate(payload: { id: number }, done: VerifiedCallback): Promise<any> {
    return done(null, payload);
  }
}

@Injectable()
export class UserTokenStrategy2 extends PassportStrategy(JwtStrategy, "user:token") {
  constructor(configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([UserTokenStrategy2.extractJWT, ExtractJwt.fromAuthHeaderAsBearerToken()]),
      secretOrKey: configService.get("SESSION_SECRET"),
      ignoreExpiration: false,
    });
  }
  private static extractJWT(req: FastifyRequest): string | null {
    const token = req.headers.authorization?.split(" ")[1];
    console.log("headers > ", token);
    return token;
  }

  async validate(payload: { id: number }, done: VerifiedCallback): Promise<any> {
    return done(null, payload);
  }
}

방식은 2가지

1. token을 그대로 받아서 처리하거나

2. token이 session이나 cookie에 들어 있거나, ws에서 전달 받을 경우, authorization에서 처리가 어려울 경우 token을 꺼내서 진행시켜주는 2번

 

UserTokenStrategy
@UseGuards(UserTokenAuthGuard)


@Module({
  providers: [AppService, AwsService, UserTokenStrategy],
})
export class AppModule {}

샘플코드라서 그런건데... UserTokenStrategy를 AuthModule에 반드시 추가해줘야됩니다.

** AuthService에서 의존성 꼬이는 문제 있었던가... 확인 필요

 

 

현재까지 코드 보기: https://github.com/close852/nestjs-toy/tree/10

반응형