본문 바로가기
Node.js/NestJs

[User] Authentication #3 JWT Middleware

by Ykie 2023. 4. 8.
728x90

사용자에게 전달된 token의 정보를 어떻게 받을 수 있을까? 

 

JWT middleware 작성 / 적용

// jwt.middleware.ts
@Injectable()
export class JwtMiddleware implements NestMiddleware {}

// 미들웨어에 추가
// #1 app.module.ts
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(JwtMiddleware)
      .forRoutes({ path: '/graphql', method: RequestMethod.ALL });
  }
}

path: '*' 전체 route에 적용할 수도 있고,
method를 통해 특정 request method만 적용할 수도 있다 (POST, PUT ...)
.forRoutes 말고 exclude를 통해 특정 route만 제외할 수도 있다.

// #2 main.ts
async function bootstrap() {
  ...
  app.use(JwtMiddleware); // 모든 application에서 사용.
  ...
}

app.use() 를 통해 사용하려면 추가하려는 middleware가 함수형이어야만 가능하다.

 

user.service.ts 에 id 값으로 user를 찾는 함수 추가

async findById(id: number): Promise<User> {
  return this.users.findOne({ where: { id } });
}

 

Jwt Middleware에 적용

@Injectable()
export class JwtMiddleware implements NestMiddleware {
  constructor(
    private readonly jwtService: JwtService,
    private readonly userService: UsersService,
  ) {}
  async use(req: Request, res: Response, next: NextFunction) {
    if ('x-jwt' in req.headers) {
      const token = req.headers['x-jwt'];
      try {
        const decoded = this.jwtService.verify(token.toString());
        if (typeof decoded === 'object' && decoded.hasOwnProperty('id')) {
          const user = await this.userService.findById(decoded['id']);
          req['user'] = user;
        }
      } catch (error) {}
    }
    next();
  }
}

 

위 방법은 별로.. 
그래서 Guard를 사용한다.! #4 에서 계속~ 

 

 

class implements, extends 차이?
: 일반클래스와 추상클래스를 상속할때는 extends를 사용하고 interface를 상속할 때는 implements를 사용한다. class가 interface를 상속받을땐 implements가 될 것이고, interface가 class를 상속받을땐 extends를 사용하게 된다.
상속을 위해서 오버라이딩이 없는 extends를 사용하지만 다중 상속을 위해서는 implements를 사용해야하고, 
implements는 클래스 단위가 아닌 interface를 상속할때 사용이 되므로, 정확한 개념의 이해가 필요할듯 하다.

Implements
부모의 클래스를 현재 자식의 클래스 내에서 한번 재정의 해줄 필요가 있다. 
우리가 아는 상속이라면 그냥 가져다 써야하는데 그것이 아니라 재정의를 해주면 그게 무슨 상속이냐 라고 할수도 있지만. 이것이 상속이라고 java에서는 정의를 내려놓았다

Extends
우리가 알고 있는 상속에 좀더 가깝다. 
부모의 메서드를 그대로 사용할수 있으며 오버라이딩 필요없이 부모에 구현되어있는것을 직접 사용가능하다. 하지만 extends는 단 하나의 클래스만 상속이 가능하다.

클래스는 단일 클래스 상속을 위해 extends, 인터페이스를 상속하기 위해는 implements 인터페이스는 인터페이스를 상속하기 위해 extends 를 사용한다.

[출처 : https://thenicesj.tistory.com/133]

 

728x90

댓글