← Back to list

Unlocking the Power of JWT Authentication with Passport.js:

JSON Web Tokens (JWT) are a fundamental aspect of modern web development, playing a crucial role in secure data exchange and user…

Debashis Kar Suvra · 2023-10-01 16:25 · 0 claps · 3.2 min read
#jwt-auth #jwt-authentication #passportjs #nodejs #expressjs
Open on Medium ↗
Wiki topics: 🌐 · Web Development 📰 · Journalism & News

Unlocking the Power of JWT Authentication with Passport.js: Secure, Elegant, and Hassle-Free User Authentication

Passport JWT

Passport JWT

JSON Web Tokens (JWT) are a fundamental aspect of modern web development, playing a crucial role in secure data exchange and user authentication. In this comprehensive guide, we will delve into JWTs, breaking down the concepts into straightforward terms, providing concrete examples, and explaining their functionality without resorting to complex technical jargon.

At its core, a JSON Web Token (JWT) is a standardized format for safely transmitting information between different parties. Think of it as a digital passport, containing essential claims about a user or entity. These claims can include user details, access permissions, and more, all stored in a simple, readable format.

A JWT comprises three primary components, separated by dots: the Header, Payload, and Signature.

  1. Header: The header serves as metadata, typically consisting of two key parts — the token type (JWT) and the signing algorithm in use (e.g., HMAC SHA256 or RSA).
  2. Payload: The payload contains the claims, which are essentially statements about an entity (usually a user) and any additional data. Claims fall into three categories:
  • Registered Claims: These are predefined claims such as “iss” (issuer), “sub” (subject), “exp” (expiration time), and others.
  • Public Claims: These are custom claims created by users, although they are not mandatory.
  • Private Claims: These are custom claims used to share information between parties that agree to use them.
  1. Signature: The signature is critical for verifying both the sender’s authenticity and the message’s integrity. It is created by combining the encoded header, encoded payload, and a secret key, using the algorithm specified in the header.

Let’s walk through a simplified step-by-step process to understand how JWTs work:

  1. Authentication: When a user logs in, the server generates a JWT containing user information and signs it using a secret key.
  2. Authorization: The server sends this JWT back to the user’s device, which securely stores it.
  3. Subsequent Requests: Whenever the user makes a request to a protected resource (e.g., accessing their profile), they include the JWT in the request header.
  4. Verification: The server receives the JWT, extracts the payload, and verifies the signature using its secret key. If the signature is valid and the token hasn’t expired, the server grants access to the protected resource.

Passport-JWT simplifies the process of integrating JWT-based authentication into your Node.js application, offering a flexible and modular approach to securing your routes. It’s a valuable tool for developers seeking to implement robust authentication mechanisms with minimal boilerplate code.Now let's move on to the passport jwt strategy.

Prerequisites

Before diving into the implementation, make sure you have the following installed:

  • Node.js and npm
  • Express.js
  • Passport
  • passport-jwt
  • jsonwebtoken
  • body-parser
  • cors

Setting Up the Server

Let’s start by setting up the server in Node.js using Express. We’ll also configure Passport with a JWT strategy.

// Import required modules
const express = require("express");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
const passport = require("passport");
const passportJWT = require("passport-jwt");
const cors = require("cors");
const users = require("./UserDB"); // Assuming you have a UserDB module

// Extract necessary objects and variables
const ExtractJwt = passportJWT.ExtractJwt;
const JwtStrategy = passportJWT.Strategy;
const PORT = process.env.PORT || 5000;

// JWT Options
const jwtOptions = {
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: "secret",
};

// JWT Strategy Configuration
const strategy = new JwtStrategy(jwtOptions, (jwt_payload, next) => {
  const user = users.find((u) => u.id === jwt_payload.id);
  if (user) {
    next(null, user);
  } else {
    next(null, false);
  }
});

passport.use(strategy);

// Create Express app
const app = express();

// Middleware setup
app.use(cors());
app.use(passport.initialize());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Basic route for checking if the server is running
app.get("/", (req, res) => {
  res.json({ message: "Express is up" });
});

// Login route for generating JWT
app.post("/login", (req, res) => {
  const { email, password } = req.body;
  const user = users.find((u) => u.email === email);

  if (!user) {
    res.status(401).json({ message: "No such user/email ID found" });
    return;
  }

  if (user.password === password) {
    const payload = { id: user.id };
    const token = jwt.sign(payload, jwtOptions.secretOrKey);
    res.json({ message: "OK", token: token });
  } else {
    res.status(401).json({ message: "Passwords did not match" });
  }
});

// Protected route using Passport JWT middleware
app.get(
  "/protected",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    res.json("Protected Route");
  }
);

// Start the server
app.listen(PORT, () => console.log(`Listening to port ${PORT}`));

In this blog post, we’ve covered the essential steps to implement secure authentication in a Node.js application using Passport and JWT. This combination provides a robust and scalable solution for user authentication in web development. Feel free to customize this setup based on your project requirements and explore additional features offered by Passport and JWT.

If you have enjoyed this article and would like to buy me a coffee ☕️follow this buymeacoffee.com/suvra.

GitHub Link: https://github.com/Suvrakar/express-passport-jwt-bolierplate.git


메타데이터
post_id
785d528d9c72
slug
unlocking-the-power-of-jwt-authentication-with-passport-js-785d528d9c72
url
https://medium.com/@suvra1/unlocking-the-power-of-jwt-authentication-with-passport-js-785d528d9c72
canonical_url
https://medium.com/@suvra1/unlocking-the-power-of-jwt-authentication-with-passport-js-785d528d9c72
author_url
https://medium.com/@suvra1
status
ok
fetched_at
2026-06-12 07:40:50