NestJS: cookie based JWT authentication

오픈소스·2023년 2월 2일
1
post-thumbnail
$ npm install --save cookie-parser
$ npm install --save-dev @types/cookie-parser

기존에 Authorization Header에서 가져 오던 JWT 토큰을 cookie에서 가져 오는 것으로 JwtStrategy 변경

src/auth/jwt.strategy.ts

...
      jwtFromRequest: ExtractJwt.fromExtractors([
        (request) => {
          return request?.cookies?.token;
        },
      ]),
...

OAuth callback에서 JWT 토큰 cookie 설정

src/auth/auth.controller.ts

...
  async callback(@User() user: UserDto, @Res() res: Response) {
    const { access_token } = await this.authService.login(user);
    res.cookie('token', access_token, { httpOnly: true });
    res.redirect('/user/protected');
  }
...

cookie Parser 실행

src/main.ts

...
  app.use(cookieParser());
...

참고)

0개의 댓글