JWT Authentication

What is JWT?

JSON Web Token (JWT) is the industry standard for Stateless Authentication. In traditional session-based systems, the server must store each user's session in memory (RAM). With JWT, the server is "stateless"—it simply verifies a "passport" (the token) provided by the client using a secret key.


1. The Core Theory: Why JWT?


Statelessness

In a MERN stack application, your backend and frontend are often decoupled. JWTs allow the server to remain stateless, meaning it does not store a session database. Every request contains all the information needed to identify the user.

Anatomy of a JWT

A token consists of three parts separated by dots (.):

  • Header: Specifies the algorithm used, such as HS256.

  • Payload: Contains the "Claims," which are pieces of user data like id and email. Note: This is only Base64 encoded, not encrypted, so never store passwords here.

  • Signature: This is the hash of the encoded header, payload, and your JWT_SECRET. If any part of the payload is changed, the signature becomes invalid.

2. The Implementation Process


Phase A: Token Generation

When a user logs in, the server validates their credentials using BcryptJS.

  • Bcrypt Theory: Passwords should never be stored in plain text. Bcrypt uses a "salt" to hash passwords, making them resistant to rainbow table attacks.

  • Process: Once validated, jwt.sign() creates the token with an expiration time (e.g., '1h') to ensure that if a token is stolen, it is only useful for a limited time


const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

// Helper function to generate a signed token
const generateToken = (id) => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: '1h'
  });
};

Phase B: Login Controller Example

This controller handles the user's attempt to log in by checking their credentials and issuing a token.


exports.login = async (req, res) => {
  const { email, password } = req.body;
  
  // Replace this with your actual Database logic (e.g., User.findOne)
  const user = await User.findOne({ email });

  if (user && (await bcrypt.compare(password, user.password))) {
    res.json({
      token: generateToken(user._id)
    });
  } else {
    res.status(401).json({ message: 'Invalid credentials' });
  }
};


Phase C: Token Storage & Headers


The server sends the token to the client (React), which must store it:

  • LocalStorage: Easy to implement but vulnerable to XSS.

  • HttpOnly Cookies: More secure as they cannot be accessed via JavaScript.

For subsequent requests to protected routes, the client sends the token in the Authorization Header using the Bearer schema: Authorization: Bearer <your_token_here>

3. The Middleware & Request Flow


The Middleware acts as a Gatekeeper between the incoming request and your final route logic.

The Process Step-by-Step:

  1. Extraction: The middleware looks at the headers and splits the "Bearer " string to get the token.

  2. Verification: jwt.verify() uses your JWT_SECRET to decode the token. It throws an error if the secret is wrong or the token has expired.

  3. Attachment: If verified, the decoded user info is attached to the req object (e.g., req.user = decoded).

  4. Handoff: next() is called to allow the request to proceed to the controller.



const jwt = require('jsonwebtoken');

const authMiddleware = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];

  if (!token) {
    return res.status(401).json({ message: 'No token provided' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded; // Attach user info to the request
    next(); 
  } catch (err) {
    res.status(401).json({ message: 'Invalid or expired token' });
  }
};

module.exports = authMiddleware;


4. Crucial Security Information


The JWT_SECRET

This is your "Master Key." If leaked, anyone can generate tokens for your system.

  • Rule: Keep this in your .env file and never commit it to GitHub.

  • Recommendation: Use a long, random string of at least 32 characters.

Error Handling

Always wrap your verification logic in a try...catch block. JWT throws specific errors like TokenExpiredError or JsonWebTokenError. Proper handling allows you to send a 401 Unauthorized status so your frontend can redirect the user to login.


Advanced Concepts

Advanced JWT: Refresh Tokens & Secure Storage


1. Access vs. Refresh Tokens (The Strategy)


Theory: Using only one long-lived token is dangerous—if stolen, a hacker has permanent access. We solve this by splitting responsibilities.

  • Access Token: A "Short-term Pass" (5–15 min) used for every request.

  • Refresh Token: A "Long-term Key" (7–30 days) kept securely by the client. It is only used to ask the server for a fresh Access Token once the old one expires.


2. Secure Storage: The HTTP-only Cookie Theory


Theory: Storing tokens in localStorage is common but risky because any malicious script (XSS) can read it.

  • HTTP-only Cookies: These are special cookies that the browser handles automatically but JavaScript cannot touch.

  • Security Process: By setting httpOnly: true, you ensure that even if an attacker injects a script into your React app, they cannot steal your user's identity.


// Sending secure cookies to the client
res.cookie('accessToken', accessToken, {
  httpOnly: true,  // Prevents XSS
  secure: true,    // Requires HTTPS in production
  sameSite: 'Strict', // Prevents CSRF attacks
  maxAge: 15 * 60 * 1000 // 15 Minutes
});


3. The Refresh Token Process


Theory: When the authMiddleware rejects a request because the Access Token has expired, the frontend calls the /refresh endpoint.

The Execution:

  1. Extraction: The server reads the Refresh Token from the user's cookies.

  2. Verification: It checks the token against a separate REFRESH_TOKEN_SECRET.

  3. Rotation (Best Practice): For maximum security, the server should invalidate the old refresh token and issue a brand new one alongside the new access token. This is called "Token Rotation".


exports.refreshToken = (req, res) => {
  const token = req.cookies.refreshToken; // Read from cookie
  if (!token) return res.status(401).json({ message: 'Session Expired' });

  try {
    const decoded = jwt.verify(token, process.env.REFRESH_TOKEN_SECRET);
    const newAccessToken = generateAccessToken({ id: decoded.id, role: decoded.role });

    // Send the new pass back via a cookie
    res.cookie('accessToken', newAccessToken, { httpOnly: true, secure: true });
    res.json({ message: 'Access Restored' });
  } catch (err) {
    return res.status(403).json({ message: 'Invalid Refresh Token' });
  }
};


4. Role-Based Access Control (RBAC)


Theory: Not all users are equal. There may be different roles.

  • The Process: We store the role inside the JWT payload.

  • The Guard: A custom middleware checks the req.user.role (attached by the auth middleware) against a list of allowed roles. If the role isn't there, the server returns a 403 Forbidden.


// Middleware to restrict access by role
const authorizeRoles = (...roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({ message: 'Access Denied' }); //[cite: 1]
    }
    next();
  };
};

// Application: Only an admin can see the admin panel
router.get('/admin', authMiddleware, authorizeRoles('admin'), (req, res) => {
  res.json({ message: "Welcome, Admin" });
});

..............................................................................................................................................................................................................