Applying Security to NestJS Applications Using JWT, Passport, and Guards

By: Freddy Manuel Sabogal

Information Security


blog/ Applying Security to NestJS Applications Using JWT, Passport, and Guards
01 June 2021


Applying Security to NestJS Applications Using JWT, Passport, and Guards


Security is a fundamental aspect of any modern application. In this blog, we will learn how to protect our routes in NestJS using Passport, JWT, and Guards.


What is NestJS?


NestJS is a progressive Node.js framework for building efficient and scalable server-side applications. It is based on TypeScript and leverages concepts such as dependency injection, modular programming, and decorator-oriented development.


What is JWT?


JWT (JSON Web Token) is an open standard (RFC 7519) that defines a compact and secure method for representing information between two parties via a JSON object.

Main Features:

  • A JWT contains data ("claims") that can be verified and trusted because they are digitally signed.
  • It is commonly used for authentication and authorization in distributed systems.
  • Its structure has three parts encoded in Base64:

    • Header: information about the signing algorithm.
    • Payload: the data or claims.
    • Signature: the signature that ensures the integrity of the token.

The structure will be:
xxxxx.yyyyy.zzzzz


What is Passport?


Passport is an extremely popular authentication middleware for Node.js applications.

Main Features:

  • Modular: uses a strategy system to authenticate requests (e.g., local login, JWT, OAuth2, Google, Facebook, etc.).
  • Minimalist: does not assume how you should manage sessions or users, it only provides the necessary tools.
  • Easy to integrate: can work with Express, NestJS, or other Node.js-based frameworks.

How it works:

  • Upon receiving a request, Passport executes a strategy (e.g., verifying the username and password or validating a JWT).
  • If authentication is successful, Passport attaches the authenticated user's data to the request object (req.user).
  • If it fails, it can throw errors or block the request automatically.

In summary:

  • Passport = "How am I going to authenticate?"
  • JWT = "What information am I going to use to prove that I am authenticated?"

nestpassport


What are we going to build?


We will implement a simple JWT authentication system:

  • User registration and login.
  • Generation of a JWT token upon login.
  • Route protection using custom Guards.


Installing dependencies:


First, create a new NestJS project:

  • nest new auth-jwt-example
  • npm install @nestjs/passport passport passport-jwt @nestjs/jwt
  • npm install --save-dev @types/passport-jwt


Configuring Passport and JWT:


First, create an AuthModule:

  • nest g module auth

And a service to handle authentication:

  • nest g service auth

Also, generate a controller:

  • nest g controller auth


AuthService:


authservice


AuthController:


authcontroller


LocalStrategy:


Passport needs strategies. We create a LocalStrategy:

localstrategy


Configuring JWT Strategy:


jwtstrategy


Creating Guards:


A Guard decides whether a request passes or not.

  • We create a guard for JWT:

jwtauthguard

  • And a guard for local login:

localauthguard


Protecting routes:


Now, suppose you have a user controller:

userscontrollers

Result: To access /users/profile, you need to send the access_token generated upon login in the Authorization header, otherwise, the service will not respond.

Authorization: Bearer your_jwt_token


Conclusion


With NestJS, Passport, and JWT, we can build a robust and secure authentication system in a very structured way. The use of Guards allows separating the authorization logic from the business logic, keeping the code clean and scalable.


Want to know more?
Schedule a call!
Contact us on WhatsApp !