Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

마로의 개발일지

NestJs JwtAuthGuard @Pulic과 함께 사용하기 본문

알게된 것

NestJs JwtAuthGuard @Pulic과 함께 사용하기

maro0201 2023. 11. 11. 16:07

 NestJs에서 인증/인가를 구현하기 위해 passport 문서를 보고 참고한 사람들이 많을 것이다. 하지만 문서에는 Extending guards에서 JwtAuthGuard를 확장하는 법만을 가르쳐 주고 바로 아래 Enable authentication globally에서는 Global 설정하는 법과 @Public을 이용해서 인증 없이 API가 호출될 수 있도록 설정하는 법만을 가르쳐줄 뿐 동시에 사용하는 법을 알려주진 않는다.

 조금만 생각해보면 당연한 사실일 수도 있지만, 나는 약간의 삽질을 한 뒤에 깨달았기 때문에 혹시나 누군가에게 도움이 되길 바라며 코드를 첨부한다.

import {
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(private reflector: Reflector) {
    super();
  }

  canActivate(context: ExecutionContext) {
    // @Public 설정시 로그인 없이 호출 가능
    const isPublic = this.reflector.getAllAndOverride<boolean>(
      constants.IS_PUBLIC_KEY,
      [context.getHandler(), context.getClass()],
    );
    if (isPublic) {
      return true;
    } else {
      // 여기 부분이 생각하기 어려웠다. 지금 보니 예시에도 잘 나와있긴 하지만...
      return super.canActivate(context);
    }
  }

  handleRequest(err, user, info) {
    // You can throw an exception based on either "info" or "err" arguments
    if (err || !user) {
      throw err || new UnauthorizedException();
    }
    return user;
  }
}

// constants.IS_PUBLIC_KEY = 'isPublic'
export const Public = () => SetMetadata(constants.IS_PUBLIC_KEY, true);

 

 

Comments