NestJS JWT Login

Gyus·2022년 5월 19일
0

JWT Login

  1. Front 에서 Login Request를 보낸다.
  2. Back 에서 LoginAPI로 JWT를 생성한다.
  3. Response로 받아서 Front에서 LocalStorage에 저장한다.

패키지 설치

$ npm install --save @nestjs/passport passport passport-local
$ npm install --save-dev @types/passport-local
  • userId/password 기반은 passport-local을 사용
  • JWT 체크 passport-jwt 사용

auth module

$ nest g module auth
$ nest g service auth
  • jwt관련 모듈로 따로 관리하기 위해서
import { forwardRef, Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { UsersModule } from '../users/users.module';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from './jwt/jwt.strategy';

@Module({
  imports: [
    //* JwtService를 사용하기위해서 import 해준다.
    JwtModule.register({
      secret: process.env.SECRET_KEY,
      signOptions: { expiresIn: '1y' },
    }),
    forwardRef(() => UsersModule),
  ],
  providers: [AuthService, JwtStrategy],
  exports: [AuthService],
})
export class AuthModule {}
  • secret은 중요하기 때문에 env처리해준다.
  • UsersModule과 순환참조 모듈 이기때문에 forwardRef처리해준다.

controller

export class UsersController {
  constructor(
    private readonly userService: UsersService,
    private readonly authService: AuthService,
  ) {}


  @Post('login')
  async logIn(@Body() userLoginDTO: UserLogInDTO) {
    console.log(userLoginDTO);
    return await this.authService.verifyUser(userLoginDTO);
  }
}
  • login시 DTO에 담아 authService의 verfifyUser에 넘겨준다.

Service(auth)

@Injectable()
export class AuthService {
  constructor(
    private userService: UsersService,
    private jwtService: JwtService,
  ) {}
  async verifyUser(userLoginDto: UserLogInDTO) {
    const { email, password } = userLoginDto;

    //* 해당하는 email이 있는가
    const user = await this.userService.findUserByEmail(email);
    if (!user) {
      throw new UnauthorizedException('이메일과 비밀번호를 확인해주세요');
    }

    //* password 일치하는가
    const isPasswordValidated: boolean = await bcrypt.compare(
      password,
      user.password,
    );
    if (!isPasswordValidated) {
      throw new UnauthorizedException('이메일과 비밀번호를 확인해주세요.');
    }

    const payload = { email: email, sub: user.id };

    return {
      token: this.jwtService.sign(payload),
    };
  }
}
  • email과 password 검증을 해준다.
  • payload에 email과 user.id를 담아서 JWT토큰을 만든다.


https://jwt.io/ 에서 확인 가능하다.


https://docs.nestjs.com/security/authentication#jwt-functionality

profile
푸로구래머

0개의 댓글