Let's make Authorization and Authentication easy for you in NodeJS

🔑 Understanding JWT Authentication & Authorization

It took me years to properly understand JWT (JSON Web Token) authentication and authorization. The reason? Theory and practicals were never taught together. I knew the definitions, but I couldn’t really connect them to actual code or real-world situations.

So here I am, to teach you practically and simply—no jargon overload! 🚀

🏢 Real-World Analogy First

Imagine you work at a company:

  • Authentication → Your face is checked at the office gate. If your face matches what’s in the system, you are authenticated (yes, you are who you claim to be).
  • Authorization → Once inside, you can only access areas you’re allowed to. For example, interns can’t open the CEO’s office. That’s authorization.

👉 In short:

  • Authentication = Who are you?
  • Authorization = What are you allowed to do?

🔐 What is JWT?

JWT stands for JSON Web Token. Think of it like a digital ID card you get after authentication.

  • You log in → The server checks your username + password → If valid, it creates a token (your digital ID).
  • That token is then sent with every request you make to the server.
  • The server uses it to know:
    • ✅ Who you are (authentication)
    • ✅ What you’re allowed to do (authorization)

⚙️ Basic Flow of JWT Authentication

  1. User logs in → sends username + password.
  2. Server verifies credentials → creates a JWT.
  3. User receives token → stores it (usually in localStorage or memory).
  4. User makes requests → sends token in Authorization header.
  5. Server checks token → If valid → grant access, else deny.

👨‍💻 Practical Example with Node.js + Express

Here’s a simple working example you can try out:


import express from "express";
import jwt from "jsonwebtoken";

const app = express();
app.use(express.json());

const SECRET = "mysecretkey";

// Step 1: Login & get token
app.post("/login", (req, res) => {
  const { username, password } = req.body;

  // Fake authentication
  if (username === "jhalak" && password === "1234") {
    const token = jwt.sign({ username, role: "user" }, SECRET, { expiresIn: "1h" });
    return res.json({ token });
  }
  res.status(401).json({ message: "Invalid credentials" });
});

// Step 2: Middleware to check token
function authMiddleware(req, res, next) {
  const authHeader = req.headers["authorization"];
  const token = authHeader && authHeader.split(" ")[1];
  
  if (!token) return res.sendStatus(401);

  jwt.verify(token, SECRET, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

// Step 3: Protected route
app.get("/dashboard", authMiddleware, (req, res) => {
  res.json({ message: `Welcome ${req.user.username}!`, role: req.user.role });
});

app.listen(3000, () => console.log("Server running on port 3000"));

  

👉 Run this, and test using Postman or cURL. - First, POST /login with {"username":"jhalak","password":"1234"} to get a token. - Then, access GET /dashboard with Authorization: Bearer <token>.

🎯 Wrap-Up

When I first heard “JWT authentication and authorization,” it felt like rocket science 🚀. But with the right analogy (office entry) and some code, it suddenly makes sense.

So the next time you hear these terms, just think:
🔓 Authentication = checking your face at the gate.
🔑 Authorization = deciding which doors you can open inside.

Made with ❤️ by Jhalak | Step-by-Step JWT Guide

Comments