Skip to main content

🎫 Understanding JWT

πŸ“– Definition​

JWT (JSON Web Token) is a JSON-based token for securely transmitting information between client and server. It consists of three parts (Header, Payload, Signature) and enables stateless authentication with excellent scalability.

🎯 Simple Analogy​

Amusement Park Ticket​

Regular Ticket (Session)
└─ Staff remembers all visitors (server burden)

VIP Ticket (JWT)
β”œβ”€ Tamper-proof stamp on ticket
β”œβ”€ Contains name, expiration, grade
└─ Staff only verifies stamp (less burden)

JWT = Information card with security seal

βš™οΈ JWT Structure​

JWT = Header.Payload.Signature

Header (algorithm info)
{
"alg": "HS256",
"typ": "JWT"
}

Payload (actual data)
{
"userId": 123,
"username": "john",
"exp": 1640086400
}

Signature (tamper protection)
HMACSHA256(header + payload, secret)

πŸ’‘ Implementation Example​

Generate and Verify JWT​

const jwt = require('jsonwebtoken');
const SECRET_KEY = 'your-secret-key';

// Generate token
function generateToken(user) {
return jwt.sign(
{ userId: user.id, username: user.username },
SECRET_KEY,
{ expiresIn: '1h' }
);
}

// Verify token
function verifyToken(token) {
try {
return jwt.verify(token, SECRET_KEY);
} catch (error) {
return null;
}
}

Login API​

const express = require('express');
const app = express();

// Login
app.post('/api/login', async (req, res) => {
const { username, password } = req.body;

// Verify user...

const token = jwt.sign(
{ userId: user.id, username: user.username },
SECRET_KEY,
{ expiresIn: '1h' }
);

res.json({ accessToken: token });
});

// Authentication middleware
function authenticateToken(req, res, next) {
const token = req.headers['authorization']?.split(' ')[1];

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

jwt.verify(token, SECRET_KEY, (err, user) => {
if (err) return res.status(403).json({ error: 'Invalid token' });
req.user = user;
next();
});
}

// Protected route
app.get('/api/profile', authenticateToken, (req, res) => {
res.json({ user: req.user });
});

πŸ€” FAQ​

Q1. JWT vs Session?​

Session: Server stores user data (memory needed)
JWT: Client stores token (stateless, scalable)

Q2. Is JWT secure?​

A: Yes, with proper usage:

βœ… Use HTTPS
βœ… Secure secret key
βœ… Short expiration (15m-1h)
βœ… Don't store sensitive data
βœ… HttpOnly cookies (prevent XSS)

Q3. Access Token vs Refresh Token?​

Access Token: Short-lived (15m), used for API requests
Refresh Token: Long-lived (7d), used to renew access token

🎬 Summary​

  • Structure: Header.Payload.Signature
  • Advantages: Stateless, scalable, cross-platform
  • Security: HTTPS, HttpOnly cookies, short lifetime
  • Pattern: Access Token + Refresh Token

Build secure authentication systems with JWT! 🎫