Script Valley
REST API Development: Complete Course from Beginner to Production
Authentication and Security in REST APIsLesson 4.1

JWT Authentication: How It Works and How to Implement It

JWT, JSON Web Token, JWT structure, header payload signature, sign token, verify token, access token, refresh token, jsonwebtoken package

JWT Authentication: How It Works and How to Implement It

JSON Web Tokens (JWT) are the most widely used authentication mechanism for REST APIs. Unlike server-side sessions, JWTs are stateless โ€” the server does not store session data. Instead, the token itself contains the user's identity and is signed by the server to prevent tampering.

DiagramJWT Authentication Flow

IMAGE PROMPT (replace this block with your generated image):

Flat numbered-step sequence diagram on white background. Title: JWT Authentication Flow. Client box on the left, Server box in the center, Database cylinder on the right. Six numbered steps with arrows. Step 1: Client โ†’ Server: arrow labeled POST /auth/login {email, password} (blue arrow #3A5EFF). Step 2: Server โ†’ Database: arrow labeled Find user + compare password hash (gray dashed arrow). Step 3: Database โ†’ Server: arrow labeled User record returned (gray dashed arrow). Step 4: Server (internal box labeled jwt.sign()): generates access_token + refresh_token. Step 5: Server โ†’ Client: arrow labeled 200 OK {access_token, refresh_token} (green arrow #22c55e). Step 6: Client โ†’ Server (subsequent requests): arrow labeled GET /api/orders / Authorization: Bearer access_token (#3A5EFF). Server box for step 6 shows jwt.verify() internally. Server โ†’ Client: 200 OK + data (green). Below the flow: three labeled boxes showing JWT structure โ€” Box 1: Header (eyJ...) with label Algorithm HS256. Box 2: Payload (eyJ...) with label {id, email, role, exp}. Box 3: Signature (SflK...) with label HMAC SHA256. Connected by dot separators. White background, clean numbered steps, brand color #3A5EFF for primary flow arrows.

JWT Structure

A JWT consists of three Base64URL-encoded parts separated by dots: header.payload.signature. The header specifies the algorithm (typically HS256 or RS256). The payload contains claims โ€” the user's ID, email, role, and expiration time. The signature is created by hashing the header and payload with a secret key, preventing forgery.

{
  "id": "507f1f77bcf86cd799439011",
  "email": "alice@example.com",
  "role": "admin",
  "iat": 1705316200,
  "exp": 1705402600
}

Implementing JWT in Express

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

const login = async (req, res) => {
  const { email, password } = req.body;
  const user = await User.findOne({ email }).select('+password');

  if (!user || !(await bcrypt.compare(password, user.password))) {
    return res.status(401).json({
      success: false,
      error: { code: 'INVALID_CREDENTIALS', message: 'Invalid email or password' }
    });
  }

  const token = jwt.sign(
    { id: user._id, email: user.email, role: user.role },
    process.env.JWT_SECRET,
    { expiresIn: '1d' }
  );

  res.status(200).json({ success: true, data: { token } });
};

JWT Verification Middleware

const protect = async (req, res, next) => {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ success: false, error: { code: 'UNAUTHORIZED' } });
  }
  try {
    const token = authHeader.split(' ')[1];
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = await User.findById(decoded.id).select('-password');
    next();
  } catch (err) {
    res.status(401).json({ success: false, error: { code: 'TOKEN_INVALID' } });
  }
};

Access and Refresh Tokens

Access tokens should have short expiry (15 minutes to 1 hour) to limit exposure if compromised. Refresh tokens have long expiry (7-30 days), are stored securely in httpOnly cookies, and are used to obtain new access tokens without re-login.

Up next

API Key Authentication and Role-Based Access Control

Sign in to track progress

JWT Authentication: How It Works and How to Implement It โ€” Authentication and Security in REST APIs โ€” REST API Development: Complete Course from Beginner to Production โ€” Script Valley โ€” Script Valley