π« 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! π«