JWT 유저 정보 반환

요청 안에 유저 정보(유저 객체)가 들어가게 하는 방법

UseGuards 안에 @nestjs/passport에서 가져온 AuthGuard()를 이용하면 요청 안에 유저 정보를 넣어줄 수 있다.

JWT 토큰을 사용해서 유저 정보를 반환해보겠다.

본래 jwt.strategy.ts로 하는데 현재 나의 경우 accessToken과 refreshToken에 대한 strategy 전략이 다르므로 액세스 토큰 strategy 파일에 다음과 같이 validate 조건을 추가하였다.

at.strategy.ts

@Injectable()
export class AtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(private authRepository: AuthRepository) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: getSecret('JWT_ACCESS_SECRET'),
    });
  }

  async validate(payload: Payload) {
    const { providerId } = payload;
    const user: Member = await this.authRepository.findUserByIdentifier(providerId);

    if (!user) {
      throw new UnauthorizedException();
    }

    return user;
  }
}

controller 단에서 실험을 해보자.

@Post('/test')
  @UseGuards(AtGuard)
  test(@Req() req) {
    console.log('req', req);
  }

Untitled

다음과 같이 테스트를 위해서는 로그인 이후 access_token을 담아서 줘야한다.