Web Application Authentication using Passport.js and JWT

By: Ronal Escobar

Information Security


blog/ Web Application Authentication using Passport.js and JWT
01 December 2023


Web Application Authentication using Passport.js and JWT


Introduction


The security of modern web applications relies on two fundamental processes: authentication and authorization. In this blog, we’ll cover how to implement both processes securely using Passport.js and JSON Web Tokens (JWT) in Node.js applications.


Authentication vs Authorization


Authentication verifies a user's identity, ensuring that they truly are who they claim to be. This typically involves asking for a username or email and a password. Once the credentials are validated, the user is considered authenticated.

On the other hand, authorization defines what actions a user can perform in the system, based on their assigned roles or permissions. A classic example would be allowing an authenticated user to view products, while only an admin can create or delete them.

autenticacion

JSON Web Token (JWT)

A JWT (JSON Web Token) is a standard format used to securely transmit signed and encoded information between two parties. It is commonly used for authenticating users, authorizing access, and maintaining stateless sessions.

It is composed of three parts:

  • Header: Token type and signing algorithm.
  • Payload: User data or 'claims'.
  • Signature: A signature created using a secret key known only to the server.

json

How a JWT Works

  1. The user authenticates (e.g., with email and password).
  2. The server generates a JWT with the user's data.
  3. The client stores the token in localStorage, sessionStorage, or cookies.
  4. The client sends the token in the Authorization header in each future request.
  5. The server verifies the token's signature and grants access.

funcionamiento jwt

Verification Middleware

A middleware in Node.js and Express allows you to run functions before a request reaches its final route. It can be used to validate authentication, check permissions, and protect endpoints using API Keys or JWTs.

verificacion

Basic example of middleware to validate JWT authentication:

ejemplo middleware

Password Hashing

Hashing converts passwords into unique values using algorithms like bcrypt. Unlike encryption, hashing is one-way and cannot be reversed. This protects passwords in case of a database breach.

password hashing

Example of using bcrypt to hash and compare passwords:

ejemplo hashing

Passport.js

passport

Passport.js is a middleware for Node.js that simplifies authentication with multiple strategies like Local, JWT, and OAuth (Google, Facebook, etc.). It allows you to add authentication without major changes to existing code.

Example of a local strategy using Passport.js:

ejemplo passport 1

ejemplo passport 2

JWT Generation and Verification

Once the user is authenticated, the server generates a JWT and sends it to the client. The client then uses it to automatically authenticate in future requests, thus maintaining secure and stateless sessions.

generacion verificacion jwt

Example of generating a JWT after successful login:

generacion jwt

Example of verifying a JWT in a protected route:

verificacion jwt

Route Protection and Role Control

Using Passport.js and JWT, you can protect sensitive routes by requiring valid tokens. You can also control access based on user roles (admin, customer, seller) specified in the JWT payload.

proteccion rutas jwt

control roles

Example of middleware for role control:

middelware control roles

Combined use of authentication and role control:

autenticacion control roles

Token Handling on the Client Side

The client should store the JWT in localStorage, sessionStorage, or HttpOnly cookies and send it in the Authorization header on each protected request. Its automatic sending can also be handled using interceptors in frameworks like Angular.

local storage

Example of including the JWT in a fetch request from the client:

jwt fetch

Password Recovery (NodeMailer)

NodeMailer is a Node.js library that simplifies email sending. It is essential for implementing password recovery features via secure links sent to the user's email.

recuperar password

Basic example of sending a password recovery email using NodeMailer:

node mailer

Conclusion

The combination of Passport.js and JWT provides a robust and flexible solution for authentication and authorization in Node.js applications. Implementing secure practices like password hashing, route protection, and role control is essential to safeguard sensitive data and improve the user experience.


Want to know more?
Schedule a call!

Contact us on WhatsApp