- 추가 패키지
@nestjs/passport
@types/passport
passport
passport-headerapikey
- 참고 문서
authorization을 각각 UseGuard
를 이용해 컨트롤러에 붙이고 싶지 않고, 미들웨어를 이용해서 전역으로 붙이고 싶었다.
auth.middleware.ts 파일을 만들어 준다.
import {
Injectable,
NestMiddleware,
UnauthorizedException,
} from '@nestjs/common';
import passport from 'passport';
@Injectable()
export class AuthMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: () => void) {
passport.authenticate('headerapikey', { session: false }, value => {
if (value) next();
else throw new UnauthorizedException();
})(req, res, next);
}
}
app.module.ts에 미들웨어 세팅을 해준다.
export class AppModule {
configure(consumer) {
consumer.apply(AuthMiddleware).forRoutes('*');
}
}
api-key.strategy.ts 파일을 생성해준다. (힘들어..)
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { HeaderAPIKeyStrategy } from 'passport-headerapikey';
@Injectable()
export class ApiKeyStrategy extends PassportStrategy(HeaderAPIKeyStrategy) {
constructor() {
super({ header: 'x-api-key', prefix: '' }, true, (apikey, done) => {
const API_KEYS = ['liche_lomad_api_key'];
const isValid = API_KEYS.find(key => key === apikey);
if (!isValid) {
return done(false);
}
return done(true);
});
}
}
많이 헤맸던 부분은 header: 'x-api-key'
부분이었다.
나는 키 이름을 x-api-key
로 하고싶은데, 예제에 있는 것 똑같이 apiKey
로 되어있었다.
또한 위 참고 예제들에서 super→validate사용을 하라고 되어있는데, 똑같이 따라하면 서버가 죽어버렸다.
// 401에러를 반환하지만 서버가 죽는 코드
async validate(apiKey: string, done: (error: Error | boolean, data) => void) {
const API_KEYS = ['liche_lomad_api_key'];
const isValid = API_KEYS.find(key => key === apiKey);
if (!isValid) {
return done(new UnauthorizedException(), null);
}
return done(null, true);
}
done에도 첫번째 인자에 null을 넣으면 서버가 죽었다.
그래서 위에 super에 넣어서 작업했더니 서버도 죽지 않고, 원하는 x-api-key를 받았을 때만 데이터를 주게 되었다!
'TIL' 카테고리의 다른 글
노션 API를 공지사항에 적용해보면 어떨까? (0) | 2024.08.19 |
---|---|
token을 관리해보자! (0) | 2024.08.19 |
supertest시 :id가 500으로 떨어진다면? (0) | 2024.08.19 |
mysql typeorm으로 한방에 generate하기 (0) | 2024.08.19 |
구글 오늘 뭐먹지 챗봇 만들기 (0) | 2024.08.19 |