• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

제로초님 질문드리고싶습니다. 이런문제는 왜발생한건지 파일 캡쳐합니다 도저히 이해가 안돼네요 undefined property verify

22.07.02 16:33 작성 조회수 767

0

import {
Injectable,
ExecutionContext,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
constructor(
private readonly jwtService: JwtService, // @Inject(forwardRef(() => AdminsService)) // private readonly adminsService: AdminsService,
) {
super();
}

canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();

const { authorization } = request.headers;

if (authorization === undefined) {
throw new HttpException('Token 전송 안됨', HttpStatus.UNAUTHORIZED);
}

//const token = authorization.replace('Bearer ', authorization);
const token = authorization.replace('Bearer ', '');
//console.log(token, 'token!!!');

request.user = this.validateToken(token);
return true;
}

validateToken(token: string) {
const secretKey = process.env.SECRET ? process.env.SECRET : 'dev';

try {
const data = this.jwtService.verify(token, {
secret: secretKey,
});
console.log(data, '11번가데이터');
return data;
} catch (e) {
switch (e.message) {
// 토큰에 대한 오류를 판단합니다.
case 'INVALID_TOKEN':
case 'TOKEN_IS_ARRAY':
case 'NO_USER':
throw new HttpException('유효하지 않은 토큰입니다.', 401);

case 'EXPIRED_TOKEN':
throw new HttpException('토큰이 만료되었습니다.', 410);

default:
console.trace(e);
// console.log('광섭짱과 함께하는 코딩공부',)
throw new HttpException('서버 오류입니다.', 500);
}
}
}
}
 
이부분은 jwt.guard.ts 입니다 저 빨간줄에서
 
Trace: TypeError: Cannot read properties of undefined (reading 'verify') 이렇게 나오는데 왜 저렇게 나오는건지 도저히 모르겠네요
해당 토큰값도 잘 받아와서 verify 를 이용해 토큰 유효성 검사를 진행하려하는데 그부분에서 에러가 계속 납니다... 도와주세요

답변 3

·

답변을 작성해보세요.

0

soonswan님의 프로필

soonswan

2023.05.25

혹시 해당 문제 해결되었을까요?.?

이건 JwtAuthGuard를 모듈에 연결하지 않았거나, JwtAuthGuard를 쓰는 모듈에서 JwtService를 provider에 넣지 않은 것입니다.

0

현재 이렇게 Authmodule쪽을 쓰고 있습니다..

https://stackoverflow.com/a/68938087

이런 식으로 해보세요.

0

모듈에서 jwtService 주입 안하신 것 같은데요?? provider나 모듈에서요.

import {
Injectable,
ExecutionContext,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();

const { authorization } = request.headers;
const jwt = JwtService;
console.log(jwt);
if (authorization === undefined) {
throw new HttpException('Token 전송 안됨', HttpStatus.UNAUTHORIZED);
}

//const token = authorization.replace('Bearer ', authorization);
const token = authorization.replace('Bearer ', '');
//console.log(token, 'token!!!');

request.user = this.validateToken(token);
return true;
}

async validateToken(token: string) {
const secretKey = process.env.SECRET ? process.env.SECRET : 'dev';

try {
console.log(123);
console.log(token);
console.log(123);
console.log(secretKey);
console.log(123);
const jwt = new JwtService();
console.log(jwt);
const verify = jwt.verify(token, { secret: secretKey });
console.log('verify', verify);
return verify;
} catch (e) {
switch (e.message) {
// console.log((e.message).stack);
// 토큰에 대한 오류를 판단합니다.
case 'INVALID_TOKEN':
case 'TOKEN_IS_ARRAY':
case 'NO_USER':
throw new HttpException('유효하지 않은 토큰입니다.', 401);

case 'EXPIRED_TOKEN':
throw new HttpException('토큰이 만료되었습니다.', 410);

default:
console.log((<Error>e).stack, '???');
        throw new HttpException('서버 오류입니다.', 500);
}
}
}
}
제로초님말씀대로 해보았는데도 불구하고 사라지지않아서 위에 콘솔을 찍어보니 constructor 에서 private jwtService
가 아예 undefined더 라구요... 저렇게 말고 할수있는방법이 있을까요.. 자꾸 귀찮게 해서 죄송합니다..

모듈을 보여주세요~