Home Projects Portfolio Dashboard Export PDF Log in

Securing NestJS Endpoints: Implementing JWT Authentication

Securing API endpoints is the gatekeeper moment for any SaaS platform. In the crm-saas-backend project, we recently focused on shifting from open access to a robust, identity-aware architecture using NestJS and JWTs.

The Challenge

As we scale our CRM capabilities, protecting sensitive business logic within our controllers became a priority. We needed a way to ensure that only authenticated requests could access specific resource routes, all while maintaining the clean separation of concerns required by our Hexagonal Architecture.

The Implementation

To bridge the gap between our authentication service and our API routes, we implemented custom guards in NestJS. This ensures that the authentication logic is decoupled from the business domain.

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  canActivate(context: ExecutionContext): boolean | Promise<boolean> {
    return super.canActivate(context) as boolean | Promise<boolean>;
  }
}

By leveraging the built-in Passport strategy, we can protect specific controller methods with minimal overhead:

@Controller('leads')
export class LeadsController {
  @UseGuards(JwtAuthGuard)
  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.leadsService.findById(id);
  }
}

Integrating Swagger Documentation

One of the benefits of using NestJS is the ability to easily maintain API documentation. Since we are now using guards, we needed to make sure our Swagger UI reflects that these endpoints require authentication.

@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('leads')
export class LeadsController { /* ... */ }

Using @ApiBearerAuth() in combination with our guard allows us to automatically signal to frontend teams which endpoints require a JWT token, reducing integration friction.

The Lesson

Authentication is not just about blocking access; it is about establishing a secure contract between the client and the server. By encapsulating our security logic inside guards, we keep our controllers lean and our domain logic isolated, which is the cornerstone of our Hexagonal Architecture approach.

Key Takeaway

Start your security implementation by centralizing your auth logic in guards. This makes it trivial to secure new routes later and ensures that your authentication mechanism remains consistent across your entire application.


Generated with Gitvlg.com

Securing NestJS Endpoints: Implementing JWT Authentication
SOFIA DESIREE BARTOLI

SOFIA DESIREE BARTOLI

Author

Share: