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.
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.
How a JWT Works
- The user authenticates (e.g., with email and password).
- The server generates a JWT with the user's data.
- The client stores the token in localStorage, sessionStorage, or cookies.
- The client sends the token in the Authorization header in each future request.
- The server verifies the token's signature and grants access.
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.
Basic example of middleware to validate JWT authentication:
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.
Example of using bcrypt to hash and compare passwords:
Passport.js
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:
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.
Example of generating a JWT after successful login:
Example of verifying a JWT in a protected route:
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.
Example of middleware for role control:
Combined use of authentication and role control:
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.
Example of including the JWT in a fetch request from the client:
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.
Basic example of sending a password recovery email using NodeMailer:
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