Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 42 ยท Building Real APIs

Authentication with JWT

Build JWT authentication in NestJS: hash passwords, sign tokens with JwtService, write an auth guard, rotate refresh tokens and see how Passport fits in.

Almost every real API has to answer two questions: who is calling? (authentication) and what may they do? (authorization, covered in Guards and Authorization). A very common answer to the first question is the JSON Web Token, or JWT: after a successful login the server hands the client a small signed token, and the client sends it back on every request.

Nest does not force one approach. The official @nestjs/jwt package gives you a JwtService that signs and verifies tokens, and @nestjs/passport plugs Nest into the Passport ecosystem when you want ready-made strategies. In this lesson you build the classic flow by hand: hash the password, log in, sign a token, protect routes with a guard, and add refresh tokens.

The real packages need Node and npm, so the Nest snippets are read-only. The runnable parts use node:crypto to reproduce the mechanics: password hashing and a JWT signed and verified from scratch.

The JWT login flow

Login Check the password, sign a token.
Token The client stores it.
Guard Verifies it on each request.

The server stays stateless, with no session lookup.

1 / 2

Never store plain passwords

Before any token exists, the user has a password, and your database must never hold it as text. Store a slow, salted hash instead. In Nest projects people usually use bcrypt or argon2 from npm:

TypeScript
import * as bcrypt from 'bcrypt';

const hash = await bcrypt.hash(plainPassword, 12); // store this
const ok = await bcrypt.compare(attempt, hash);     // check a login

Two ideas matter here. A salt is random data mixed into each hash, so two users with the same password get different hashes. A slow algorithm makes guessing millions of passwords expensive for an attacker. Fast hashes such as plain SHA-256 are the wrong tool for passwords.

The first stand-in uses scrypt from node:crypto, which is a slow, salted password hash that ships with Node. It is not what bcrypt does internally, but the shape of the code is the same.

Node.js Salted password hashing with scrypt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

timingSafeEqual compares two buffers in constant time, so an attacker cannot learn how many leading bytes matched from how long the comparison took. bcrypt.compare does this for you.

Setting up JwtService

Install @nestjs/jwt and register the module in the module that owns authentication. The secret must come from configuration, never from source code (see Configuration and Environment):

TypeScript
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';

@Module({
  imports: [
    UsersModule,
    JwtModule.registerAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        secret: config.getOrThrow<string>('JWT_SECRET'),
        signOptions: { expiresIn: '15m' },
      }),
    }),
  ],
  providers: [AuthService],
  controllers: [AuthController],
  exports: [AuthService],
})
export class AuthModule {}

registerAsync is a dynamic module pattern: the secret is read when the app boots. A short expiresIn keeps a leaked access token useful only for a few minutes.

The login flow

AuthService finds the user, compares the password and signs a token. The payload holds claims. By convention sub (subject) carries the user id, and you add only what the guard needs, such as a role:

TypeScript
@Injectable()
export class AuthService {
  constructor(
    private readonly users: UsersService,
    private readonly jwt: JwtService,
  ) {}

  async login(email: string, password: string) {
    const user = await this.users.findByEmail(email);
    const valid = user && (await bcrypt.compare(password, user.passwordHash));
    if (!valid) {
      throw new UnauthorizedException('Invalid credentials');
    }
    const payload = { sub: user.id, role: user.role };
    return { access_token: await this.jwt.signAsync(payload) };
  }
}

Notice that the same error is thrown whether the email is unknown or the password is wrong. Telling the two cases apart would let an attacker discover which emails have accounts.

TypeScript
@Controller('auth')
export class AuthController {
  constructor(private readonly auth: AuthService) {}

  @Post('login')
  @HttpCode(200)
  login(@Body() dto: LoginDto) {
    return this.auth.login(dto.email, dto.password);
  }
}

What a JWT really is

A JWT is three base64url strings joined by dots: header.payload.signature. The header names the algorithm (for example HS256, an HMAC with SHA-256), the payload holds the claims, and the signature is the HMAC of the first two parts under your secret. Anyone can read the payload, so never put secrets in it. Only someone with the secret can produce a signature that verifies.

The next stand-in signs and verifies a token from scratch. The clock is passed in, so the output is the same on every run.

Node.js Sign and verify a JWT by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real libraries do the same work, plus more checks (the nbf claim, issuer, audience). One lesson stands out: the verifier fixes the allowed algorithm itself and never trusts the algorithm named in the token. Accepting whatever the header says has caused real vulnerabilities in the past.

The auth guard

Now protect routes. A guard reads the Authorization: Bearer <token> header, verifies it with JwtService and attaches the payload to the request so handlers can use it:

TypeScript
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly jwt: JwtService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    if (type !== 'Bearer' || !token) {
      throw new UnauthorizedException();
    }
    try {
      request.user = await this.jwt.verifyAsync(token);
    } catch {
      throw new UnauthorizedException();
    }
    return true;
  }
}

Apply it per route with @UseGuards(AuthGuard), or register it globally with the APP_GUARD token and mark public routes with a custom decorator that a Reflector reads. A global guard with an opt-out is safer than remembering to add the guard everywhere: a forgotten route stays protected.

Refresh tokens

A short-lived access token limits damage but forces users to log in every 15 minutes. The usual fix is a second, long-lived refresh token. The client uses it only to ask for a new access token, so it travels rarely.

A sound design has these rules:

  • The refresh token is opaque and random (or a JWT with a different secret), stored hashed in the database like a password.
  • It is rotated: every refresh issues a new one and invalidates the old one.
  • If an old refresh token is ever used again, treat it as theft and revoke the whole session.
  • Logout deletes it on the server, something a pure access-token setup cannot do.

The stand-in below keeps a refresh-token store in memory and shows rotation and reuse detection.

Node.js Refresh token rotation and reuse detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The replay of first is exactly the signal that a token leaked: a legitimate client already exchanged it. Revoking the session forces a fresh login for the real user and locks the thief out.

Passport strategies in a nutshell

Passport is a Node library with hundreds of "strategies" (local username and password, JWT, Google, GitHub and so on). @nestjs/passport wraps it:

TypeScript
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(config: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: config.getOrThrow('JWT_SECRET'),
    });
  }

  validate(payload: { sub: number; role: string }) {
    return { id: payload.sub, role: payload.role };
  }
}

You then protect routes with AuthGuard('jwt') from @nestjs/passport, and whatever validate returns becomes request.user. Choose Passport when you need social login or several strategies. For a plain JWT API, the hand-written guard above is smaller and has fewer moving parts. Both are valid.

Security checklist

  • Keep the secret in configuration, long and random; rotate it if it leaks. Consider asymmetric keys (RS256, ES256) if other services must verify tokens without being able to sign them.
  • Use short access-token lifetimes and rotate refresh tokens.
  • Never put passwords or private data in the payload.
  • Rate-limit the login route (see Caching, Throttling and Scheduling).
  • Send tokens over HTTPS only. If you store a token in a browser, know the trade-offs: localStorage is readable by injected scripts, while an HttpOnly cookie needs CSRF protection.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a login endpoint return the same error for an unknown email and a wrong password?

    Different messages leak whether an account exists. A single generic 401 gives an attacker nothing to enumerate.
  2. 2. What does the signature of a JWT protect?

    The payload is only base64url-encoded, so anyone can read it. The HMAC signature detects tampering.
  3. 3. Which refresh-token design is the safest?

    Hashing protects a leaked database, rotation shortens the useful life of each token, and reuse detection reveals theft.
  4. 4. In an auth guard, where do you usually read the token from?

    Clients send the access token in the Authorization header with the Bearer scheme, and the guard reads it from the request.

Summary

  • Hash passwords with a slow, salted algorithm such as bcrypt or argon2; compare with a constant-time check.
  • JwtService.signAsync creates a token from claims (sub, role) and verifyAsync checks signature and expiry; configure the secret through ConfigService.
  • A JWT is header.payload.signature: readable by anyone, but unforgeable without the secret.
  • An AuthGuard extracts the Bearer token, verifies it and sets request.user; a global guard with a public opt-out is the safest default.
  • Short-lived access tokens plus rotated, hashed refresh tokens balance safety and convenience.
  • Passport adds ready-made strategies when you need them; it is optional for a plain JWT API.

Continue with OpenAPI and Swagger Docs to document the endpoints you have built.