Learn NestJS Β· 7/14

Securing Your App: Authentication

9 min read

Hello there, future NestJS security expert! πŸ§™β€β™‚οΈ

Welcome to the guide on securing your application. Today, we're moving from a world where our app trusts everyone to a more... exclusive club, where you need a special pass to get in. We'll be building the bouncer, the VIP pass, and the doorman for our NestJS app. Let's get started!


So, What's the Big Deal with Authentication?

The Problem: Imagine you've built a fantastic social media app. Users can post their thoughts, share pictures of their pets, and chat with friends. But there's a problem. How do you know who is posting what? How do you make sure only you can delete your posts and not someone else's? Right now, every request to your server is anonymous. It's like a masquerade ball where you can't tell who's who. This is a big security and functionality problem.

The Solution: Authentication. Authentication is the process of verifying who a user is. It's the digital equivalent of checking someone's ID at the door. By authenticating users, we can give them secure access to their own data and actions, making our application safe and personalized.


1. Authentication Strategies: JWT and Passport.js πŸ›‘οΈ

To solve our "who is who" problem, we need a system. We can't just ask for a user's password with every single click they make. That would be incredibly annoying and insecure.

The Problem: Stateless Identity Crisis

HTTP, the protocol of the web, is stateless. This means every request is a brand new interaction. The server has no memory of previous requests. If a user logs in, the server immediately forgets who they are on the very next request. How do we create a persistent "logged-in" session in this forgetful world?

Solution Part 1: JSON Web Tokens (JWT) - Your Digital VIP Pass

A JWT is a compact, secure way to represent a user's identity.

Analogy Time: Think of a high-tech, exclusive resort. When you check in (log in with your username and password), the front desk gives you a special, tamper-proof wristband (the JWT). This wristband contains your name and access level (the payload). To get into the VIP lounge or the pool (protected routes), you don't need to show your ID again. You just flash the wristband. The bouncers (our server) can quickly scan it, verify it's authentic (the signature), and let you in.

A JWT has three parts separated by dots (.):

  1. Header: Contains metadata, like the type of token and the signing algorithm used.
  2. Payload: Contains the "claims" or data about the user (e.g., user ID, username). This is the info on your wristband.
  3. Signature: A cryptographic signature that verifies the token hasn't been tampered with. Only the server has the secret key to create this signature.

Solution Part 2: Passport.js - The Master of Ceremonies

Passport.js is an authentication middleware for Node.js that is incredibly popular and flexible. Think of it as the event manager for our resort. It doesn't handle security itself, but it knows exactly which expert to call for the job.

It uses a modular concept called Strategies.

  • Want to log in with a username and password? Use the local strategy.
  • Want to validate a JWT wristband? Use the jwt strategy.
  • Want to log in with Google or Facebook? There are strategies for that too!

In NestJS, we use the @nestjs/passport module, which elegantly wraps Passport.js for a smooth, integrated experience.

Let's get our tools ready. Time for installation! πŸ’»

First, we need the core packages for handling JWTs and integrating Passport.

bash
npm install --save @nestjs/passport passport @nestjs/jwt passport-jwt
npm install --save-dev @types/passport-jwt

This installs everything we need: the NestJS wrappers, the core libraries, and the all-important TypeScript type definitions.


2. Implementing User Login and Token Generation 🎟️

Now that we understand the tools, let's build the "check-in desk" β€” the login endpoint that validates a user and hands them their shiny JWT wristband.

The Problem: How do we take a user's email and password, check if they are valid, and if so, create and return a signed JWT?

The Solution: We'll create an AuthModule, an AuthService to handle the logic, and a LocalStrategy to validate the credentials.

Step 1: Set up the AuthModule

First, we generate the necessary files with the Nest CLI:

bash
nest generate module auth
nest generate service auth
nest generate controller auth

Now, let's configure the AuthModule to use the JwtModule and PassportModule.

src/auth/auth.module.ts

typescript
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { UsersModule } from '../users/users.module'; // Assuming you have a UsersModule
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';

@Module({
  imports: [
    UsersModule, // Import so we can use UsersService
    PassportModule,
    JwtModule.register({
      secret: 'YOUR_SUPER_SECRET_KEY', // 🀫 IMPORTANT: Use an env variable for this!
      signOptions: { expiresIn: '60m' }, // Token expires in 60 minutes
    }),
  ],
  providers: [AuthService], // We will add strategies here later
  controllers: [AuthController],
})
export class AuthModule {}

Fun Fact: Using a hardcoded secret like 'YOUR_SUPER_SECRET_KEY' is great for a demo, but in the real world, it's like writing your house key code on the front door. Always use environment variables and a configuration module!

Step 2: Create the AuthService

This service will have two main jobs:

  1. validateUser(): Check if a user exists and if the password is correct.
  2. login(): If the user is valid, generate a JWT for them.

src/auth/auth.service.ts

typescript
import { Injectable } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';

@Injectable()
export class AuthService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  async validateUser(email: string, pass: string): Promise<any> {
    const user = await this.usersService.findOne(email);
    if (user && (await bcrypt.compare(pass, user.password))) {
      const { password, ...result } = user;
      return result;
    }
    return null;
  }

  async login(user: any) {
    const payload = { username: user.username, sub: user.userId };
    return {
      access_token: this.jwtService.sign(payload),
    };
  }
}

Step 3: Implement the Login Endpoint

Finally, let's create the /auth/login endpoint in the AuthController. This is where a user sends their credentials.

src/auth/auth.controller.ts

typescript
import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
import { AuthService } from './auth.service';

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

  @HttpCode(HttpStatus.OK)
  @Post('login')
  async signIn(@Body() signInDto: Record<string, any>) {
    // Note: This is simplified. In a real app, use DTOs with validation.
    const user = await this.authService.validateUser(signInDto.email, signInDto.password);
    if (!user) {
      throw new UnauthorizedException();
    }
    return this.authService.login(user);
  }
}

At this point, you can hit the /auth/login endpoint with a valid email and password, and you'll get a JWT back! You've successfully built the check-in desk.


3. Protecting Routes: Introduction to Guards πŸ’‚

You're giving out wristbands (JWTs), but none of the bouncers are checking for them yet! Anyone can still walk into the VIP lounge.

The Problem: How do we enforce that certain routes (e.g., /profile) can only be accessed by users with a valid JWT?

The Solution: NestJS Guards. A Guard is a class whose single responsibility is to determine if a request can proceed. It's literally the bouncer at the door of your route.

For JWTs, the @nestjs/passport package gives us a powerful, pre-built bouncer: the AuthGuard.

Step 1: Implement the JWT Strategy

First, we need to teach Passport how to validate our JWT. This is done with a JwtStrategy. This strategy will extract the token from the request header, verify it's legitimate using our secret key, and return the payload.

src/auth/jwt.strategy.ts (Create this new file)

typescript
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: 'YOUR_SUPER_SECRET_KEY', // Same secret as in the module!
    });
  }

  // Passport automatically calls this method after verifying the JWT signature.
  // The 'payload' is the decoded JSON from the token.
  async validate(payload: any) {
    // This is where we can attach the user to the request object.
    return { userId: payload.sub, username: payload.username };
  }
}

Don't forget to add JwtStrategy to the providers array in your auth.module.ts!

Step 2: Use the AuthGuard to Protect a Route

Now for the fun part. Let's create a /profile endpoint that should only be accessible to logged-in users. We protect it using the @UseGuards() decorator.

src/app.controller.ts (or any other controller)

typescript
import { Controller, Get, UseGuards, Request } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller()
export class AppController {

  @UseGuards(AuthGuard('jwt')) // Our bouncer is now at the door!
  @Get('profile')
  getProfile(@Request() req) {
    // Because of our JwtStrategy, req.user is now populated with the token's payload.
    return req.user;
  }
}

That's it! If you try to access /profile without a valid JWT in your Authorization: Bearer <token> header, NestJS will automatically return a 401 Unauthorized error. The bouncer is doing its job!


4. Extracting the Current User via Custom Decorators ✨

Okay, our bouncer works. Inside the getProfile handler, we can get the user info from req.user. But accessing the full request object just to get one property feels a bit clumsy.

The Problem: How can we get direct, clean access to the authenticated user object inside our route handlers without the boilerplate of req.user?

The Solution: Custom Decorators! NestJS allows you to create your own decorators to extract data from the request and inject it directly into your method parameters. This makes our controllers incredibly clean and readable.

Let's create a @GetUser() decorator.

src/auth/decorators/get-user.decorator.ts (Create a new file and folder)

typescript
import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const GetUser = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return request.user;
  },
);

How does this magic work?
createParamDecorator is a factory function from NestJS.

  1. It takes a callback function.
  2. This callback receives the ExecutionContext (which is a wrapper around the incoming request).
  3. We use ctx.switchToHttp().getRequest() to get the familiar request object.
  4. We return request.user, which is the data our JwtStrategy attached earlier.

Now, let's refactor our getProfile method to use our shiny new decorator.

src/app.controller.ts

typescript
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { GetUser } from './auth/decorators/get-user.decorator'; // Import our new decorator
import { User } from './users/user.entity'; // Assuming you have a User entity for type safety

@Controller()
export class AppController {

  @UseGuards(AuthGuard('jwt'))
  @Get('profile')
  getProfile(@GetUser() user: User) { // Look how clean that is!
    console.log(user);
    return user;
  }
}

Look at that! No more @Request() clutter. The @GetUser() decorator tells NestJS, "Hey, when you call this function, please find the user object for me and pass it in as the user argument." It’s clean, declarative, and highly reusable.

And that's a wrap! You've successfully secured your application, from issuing digital passes to hiring bouncers and giving your route handlers a direct line to the authenticated user. Welcome to the club! πŸŽ‰


πŸ“š Extra Reading & References

Challenge

You are tasked with creating a JWT strategy for a NestJS application to secure your API endpoints. This strategy will be responsible for validating JSON Web Tokens sent by clients.

Requirements:

  1. Complete the JwtStrategy class which extends PassportStrategy(Strategy).
  2. In the constructor, call the super() method with a configuration object that accomplishes the following:
    • Specifies that the JWT should be extracted from the Authorization header as a Bearer token.
    • Ensures that token expiration is not ignored (i.e., expired tokens should be rejected).
    • Uses the string 'YOUR_SECRET_KEY' as the secret for verifying the token's signature.
  3. Implement the validate method. This method receives the decoded JWT payload as its argument.
  4. The incoming payload is an object with the properties: sub (the user's ID) and username.
  5. Your validate method must return an object containing just the user's ID and username, mapping sub to a userId property.

Expected result

Your final code should be a complete TypeScript class named JwtStrategy.

The constructor must invoke super() with a configuration object that correctly sets the jwtFromRequest, ignoreExpiration, and secretOrKey properties according to the instructions.

The validate method should accept the payload object and return a new object with the following structure: { userId: payload.sub, username: payload.username }.

This implementation is a critical piece of the authentication flow, as it will be used by the AuthGuard('jwt') to verify incoming requests and attach the resulting user object to the request for use in controllers.

typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.