A simple JWT-based auth using Passport and bcrypt:
- Register (
POST /auth/register):- Hash password with bcrypt and save user via TypeORM (SQLite).
- Login (
POST /auth/login):- Validate creds with Passport Local.
- Return
{ access_token }signed by NestJS JWT.
- Secure routes:
- Send
Authorization: Bearer <token>header. - Passport JWT guard verifies token and sets
req.user.
- Send
Key packages: @nestjs/passport, passport-local, @nestjs/jwt, passport-jwt, bcrypt, class-validator, TypeORM
flowchart LR
Client[Client] -->|"POST /auth/register"| AuthC[AuthController]
AuthC -->|"AuthService.register"| USerSvc[UsersService.create]
USerSvc -->|"save to DB"| DB[(SQLite DB)]
Client -->|"POST /auth/login"| LocalG[LocalAuthGuard]
LocalG -->|"validateUser"| AuthSvc2[AuthService.login]
AuthSvc2 -->|"sign JWT"| JWT[[JWT]]
Client -->|"GET /users"| JwtG[JwtAuthGuard]
JwtG -->|"verify token"| UserCtrl[UsersController]
UserCtrl -->|"findAll"| USerSvc
-
Local Strategy (Login)
- The
LocalAuthGuardtriggers Passport’sLocalStrategy. LocalStrategy.validate()callsAuthService.validateUser(username, password).- Inside
validateUser:UsersService.findOne(username)looks up the user in the SQLite DB.bcrypt.compare(password, user.password)checks the plain‐text password against the stored hash.- If it matches, the method strips out the
passwordfield and returns the user object; otherwise it returnsnull.
- Passport then either attaches the user to
req.user(success) or rejects with 401.
- The
-
JWT Issuance
- On successful login, the controller calls
AuthService.login(req.user). AuthService.login()builds a payload{ username, sub: user.id }and callsJwtService.sign().- The signed token is returned as
{ access_token: '<JWT>' }.
- On successful login, the controller calls
-
Protected Routes (Authorization)
- Clients include
Authorization: Bearer <access_token>on requests. JwtAuthGuarduses Passport’sJwtStrategy:ExtractJwt.fromAuthHeaderAsBearerToken()pulls the token from the header.- The strategy verifies the signature and expiration against the secret.
- On success,
JwtStrategy.validate(payload)returns{ userId: payload.sub, username: payload.username }. - Passport sets this object as
req.user.
- Controllers can then safely access
req.userknowing the request is authenticated.
- Clients include