Abbottabad, KPK
BlogSeptember 27, 2026

Building a Secure JWT Authentication System with NestJS, Passport & PostgreSQL

Haseeb Gul
Authentication is the backbone of every production web application. Getting it wrong � whether through insecure token storage, missing refresh token rotation, or poorly designed guards � opens your users to session hijacking, token theft, and unauthorized access. In this post, I'll walk through the exact architecture I use to implement a secure, production-ready JWT auth system with NestJS, Passport.js, and PostgreSQL. Before writing a single line of code, it's critical to understand how the pieces fit together:
Layer
Technology
Responsibility
API FrameworkNestJS (Express adapter)Route handling, DI container, Guards, Interceptors
Auth StrategyPassport.js (passport-jwt, passport-local)Strategy registration, credential validation
Token Enginejsonwebtoken via @nestjs/jwtAccess & refresh JWT signing and verification
DatabasePostgreSQL + TypeORMUser persistence, hashed passwords, refresh token storage
Password HashingbcryptjsSalted one-way password hashing (cost factor 12)
Start by scaffolding a NestJS project and installing the required packages:
Terminal
# Scaffold a new NestJS project
npx @nestjs/cli new auth-api --package-manager npm

# Core auth dependencies
npm install @nestjs/jwt @nestjs/passport passport passport-jwt passport-local
npm install @nestjs/typeorm typeorm pg bcryptjs
npm install cookie-parser

# Type definitions
npm install -D @types/passport-jwt @types/passport-local @types/bcryptjs @types/cookie-parser
Define a User entity with TypeORM. Store only hashed passwords � never plaintext.
src/users/user.entity.ts
import {
Entity, PrimaryGeneratedColumn, Column,
CreateDateColumn, UpdateDateColumn, BeforeInsert
} from "typeorm";
import * as bcrypt from "bcryptjs";

@Entity("users")
export class User {
@PrimaryGeneratedColumn("uuid")
id: string;

@Column({ unique: true, length: 100 })
email: string;

@Column()
password: string; // Always stored as bcrypt hash

@Column({ nullable: true, type: "text" })
refreshToken: string | null; // Hashed refresh token stored server-side

@CreateDateColumn()
createdAt: Date;

@UpdateDateColumn()
updatedAt: Date;

@BeforeInsert()
async hashPassword() {
  this.password = await bcrypt.hash(this.password, 12);
}

async validatePassword(plain: string): Promise<boolean> {
  return bcrypt.compare(plain, this.password);
}
}
src/auth/auth.module.ts
import { Module } from "@nestjs/common";
import { JwtModule } from "@nestjs/jwt";
import { PassportModule } from "@nestjs/passport";
import { TypeOrmModule } from "@nestjs/typeorm";
import { ConfigModule, ConfigService } from "@nestjs/config";

import { AuthService } from "./auth.service";
import { AuthController } from "./auth.controller";
import { JwtAccessStrategy } from "./strategies/jwt-access.strategy";
import { JwtRefreshStrategy } from "./strategies/jwt-refresh.strategy";
import { LocalStrategy } from "./strategies/local.strategy";
import { User } from "@/users/user.entity";

@Module({
imports: [
  TypeOrmModule.forFeature([User]),
  PassportModule,
  JwtModule.registerAsync({
    imports: [ConfigModule],
    inject: [ConfigService],
    useFactory: (config: ConfigService) => ({
      secret: config.get<string>("JWT_ACCESS_SECRET"),
      signOptions: { expiresIn: "15m" },
    }),
  }),
],
controllers: [AuthController],
providers: [AuthService, LocalStrategy, JwtAccessStrategy, JwtRefreshStrategy],
exports: [AuthService],
})
export class AuthModule {}
src/auth/strategies/local.strategy.ts
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Strategy } from "passport-local";
import { AuthService } from "../auth.service";

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
  super({ usernameField: "email" });
}

async validate(email: string, password: string) {
  const user = await this.authService.validateUser(email, password);
  if (!user) {
    throw new UnauthorizedException("Invalid credentials");
  }
  return user;
}
}
src/auth/strategies/jwt-access.strategy.ts
import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { ConfigService } from "@nestjs/config";

@Injectable()
export class JwtAccessStrategy extends PassportStrategy(Strategy, "jwt-access") {
constructor(private config: ConfigService) {
  super({
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    ignoreExpiration: false,
    secretOrKey: config.get<string>("JWT_ACCESS_SECRET"),
  });
}

async validate(payload: { sub: string; email: string }) {
  return { id: payload.sub, email: payload.email };
}
}
src/auth/strategies/jwt-refresh.strategy.ts
import { Injectable, ForbiddenException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { Request } from "express";
import { ConfigService } from "@nestjs/config";

@Injectable()
export class JwtRefreshStrategy extends PassportStrategy(Strategy, "jwt-refresh") {
constructor(private config: ConfigService) {
  super({
    jwtFromRequest: ExtractJwt.fromExtractors([
      (req: Request) => req?.cookies?.["refresh_token"] ?? null,
    ]),
    secretOrKey: config.get<string>("JWT_REFRESH_SECRET"),
    passReqToCallback: true,
  });
}

async validate(req: Request, payload: { sub: string; email: string }) {
  const refreshToken = req.cookies?.["refresh_token"];
  if (!refreshToken) throw new ForbiddenException("Refresh token missing");
  return { ...payload, refreshToken };
}
}
src/auth/auth.service.ts
import {
Injectable, ConflictException,
ForbiddenException
} from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { ConfigService } from "@nestjs/config";
import * as bcrypt from "bcryptjs";
import { User } from "@/users/user.entity";
import { RegisterDto } from "./dto/register.dto";

@Injectable()
export class AuthService {
constructor(
  @InjectRepository(User) private usersRepo: Repository<User>,
  private jwtService: JwtService,
  private config: ConfigService,
) {}

async register(dto: RegisterDto) {
  const exists = await this.usersRepo.findOneBy({ email: dto.email });
  if (exists) throw new ConflictException("Email already registered");
  const user = this.usersRepo.create(dto);
  await this.usersRepo.save(user);
  const tokens = await this.issueTokens(user.id, user.email);
  await this.saveHashedRefreshToken(user.id, tokens.refreshToken);
  return tokens;
}

async validateUser(email: string, password: string): Promise<User | null> {
  const user = await this.usersRepo.findOneBy({ email });
  if (!user || !(await user.validatePassword(password))) return null;
  return user;
}

async login(user: User) {
  const tokens = await this.issueTokens(user.id, user.email);
  await this.saveHashedRefreshToken(user.id, tokens.refreshToken);
  return tokens;
}

async refreshTokens(userId: string, rawRefreshToken: string) {
  const user = await this.usersRepo.findOneBy({ id: userId });
  if (!user || !user.refreshToken) throw new ForbiddenException("Access denied");
  const isValid = await bcrypt.compare(rawRefreshToken, user.refreshToken);
  if (!isValid) throw new ForbiddenException("Invalid refresh token");
  const tokens = await this.issueTokens(user.id, user.email);
  await this.saveHashedRefreshToken(user.id, tokens.refreshToken);
  return tokens;
}

async logout(userId: string) {
  await this.usersRepo.update(userId, { refreshToken: null });
}

private async issueTokens(userId: string, email: string) {
  const payload = { sub: userId, email };
  const [accessToken, refreshToken] = await Promise.all([
    this.jwtService.signAsync(payload, {
      secret: this.config.get("JWT_ACCESS_SECRET"),
      expiresIn: "15m",
    }),
    this.jwtService.signAsync(payload, {
      secret: this.config.get("JWT_REFRESH_SECRET"),
      expiresIn: "7d",
    }),
  ]);
  return { accessToken, refreshToken };
}

private async saveHashedRefreshToken(userId: string, token: string) {
  const hashed = await bcrypt.hash(token, 10);
  await this.usersRepo.update(userId, { refreshToken: hashed });
}
}
src/auth/auth.controller.ts
import {
Controller, Post, Body, UseGuards,
Req, Res, HttpCode, HttpStatus, Get
} from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
import { Request, Response } from "express";
import { AuthService } from "./auth.service";
import { RegisterDto } from "./dto/register.dto";

@Controller("auth")
export class AuthController {
constructor(private authService: AuthService) {}

@Post("register")
async register(
  @Body() dto: RegisterDto,
  @Res({ passthrough: true }) res: Response,
) {
  const { accessToken, refreshToken } = await this.authService.register(dto);
  this.setRefreshTokenCookie(res, refreshToken);
  return { accessToken };
}

@UseGuards(AuthGuard("local"))
@Post("login")
@HttpCode(HttpStatus.OK)
async login(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
  const { accessToken, refreshToken } = await this.authService.login(req.user as any);
  this.setRefreshTokenCookie(res, refreshToken);
  return { accessToken };
}

@UseGuards(AuthGuard("jwt-refresh"))
@Post("refresh")
@HttpCode(HttpStatus.OK)
async refresh(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
  const user = req.user as any;
  const { accessToken, refreshToken } = await this.authService.refreshTokens(
    user.sub, user.refreshToken
  );
  this.setRefreshTokenCookie(res, refreshToken);
  return { accessToken };
}

@UseGuards(AuthGuard("jwt-access"))
@Post("logout")
@HttpCode(HttpStatus.OK)
async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
  const user = req.user as any;
  await this.authService.logout(user.id);
  res.clearCookie("refresh_token");
  return { message: "Logged out successfully" };
}

@UseGuards(AuthGuard("jwt-access"))
@Get("me")
getProfile(@Req() req: Request) {
  return req.user;
}

private setRefreshTokenCookie(res: Response, token: string) {
  res.cookie("refresh_token", token, {
    httpOnly: true,
    secure: true,
    sameSite: "strict",
    maxAge: 7 * 24 * 60 * 60 * 1000,
  });
}
}
.env
# .env
DATABASE_URL=postgresql://user:password@localhost:5432/auth_db

# Generate strong secrets:
# node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
JWT_ACCESS_SECRET=your-super-secure-access-secret-64-chars-minimum
JWT_REFRESH_SECRET=your-super-secure-refresh-secret-64-chars-minimum
Production Security Takeaways
  1. Always generate JWT secrets with at least 64 random bytes � use crypto.randomBytes(64).toString("hex").
  2. Set access token expiry to 15m max and refresh tokens to 7d with rotation on every use.
  3. Store refresh tokens in HttpOnly, Secure, SameSite=Strict cookies � never in localStorage.
  4. Hash refresh tokens with bcrypt before persisting to the database.
  5. Implement logout by nullifying the stored refresh token hash � this instantly invalidates all active sessions for that user.