마로의 개발일지
NestJs JwtAuthGuard @Pulic과 함께 사용하기 본문
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);
'알게된 것' 카테고리의 다른 글
local 환경에서 server -> smart contract 호출 해보기 (0) | 2023.09.23 |
---|---|
Spring-data-MongoDB upsert시 duplicateKeyException 해결하기 (0) | 2023.05.21 |
AWS AppConfig 배포시 Lambda 호출 설정하기 (0) | 2023.04.22 |
Java에서 Aws AppConfig 사용하기 (0) | 2023.04.15 |