9. JWT (JSON Web Tokens)
What is JWT?
JWT (JSON Web Token) is a compact, URL-safe way to transmit information between parties as a JSON object. After a user logs in, the server gives them a JWT. The client sends this token with every subsequent request to prove their identity.
What Does a JWT Look Like?
A JWT is three Base64 strings separated by dots: header.payload.signature. The header contains the algorithm (HS256). The payload contains your data (userId, role). The signature cryptographically signs the first two parts to prevent tampering.
const jwt = require('jsonwebtoken'); const payload = { userId: 123, role: 'admin' }; const secret = 'mySuperSecretKey'; const token = jwt.sign(payload, secret, { expiresIn: '1h' }); console.log('Full JWT:', token); console.log('Header:', token.split('.')[0]); console.log('Payload:', token.split('.')[1]); console.log('Signature:', token.split('.')[2]);
The Three Parts Explained
The header says which algorithm was used to sign the token. The payload contains your custom data (like userId and role). Anyone can decode and read the payload, so never put secrets there. The signature is created by hashing the header and payload with a secret key. If someone modifies the payload, the signature becomes invalid.
const jwt = require('jsonwebtoken'); const token = jwt.sign({ userId: 123, name: 'Alice' }, 'secret'); const decoded = jwt.decode(token); console.log('Anyone can read this:', decoded); // Try to verify with wrong secret jwt.verify(token, 'wrongSecret', (err) => { console.log('Wrong secret:', err.message); });
Generating a JWT (Login)
After successful login, you generate a JWT containing the user's ID and role. You sign it with your secret key and send it to the client. The client stores this token and sends it with future requests.
const jwt = require('jsonwebtoken'); const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key'; function login(email, password) { const user = { id: 456, email, role: 'user' }; const token = jwt.sign( { userId: user.id, role: user.role }, JWT_SECRET, { expiresIn: '1h' } ); console.log('Send this token to the client:', token); return token; } login('alice@example.com', 'password123');
Verifying a JWT
When a protected route is accessed, you extract the token from the Authorization header. Then you verify it with jwt.verify(). If the signature is valid and the token hasn't expired, you attach the decoded user data to req.user and call next().
const jwt = require('jsonwebtoken'); function authenticate(req, res, next) { const authHeader = req.headers.authorization; if (!authHeader) { return res.status(401).json({ error: 'No token provided' }); } const token = authHeader.split(' ')[1]; try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded; next(); } catch (err) { if (err.name === 'TokenExpiredError') { return res.status(401).json({ error: 'Token expired' }); } return res.status(403).json({ error: 'Invalid token' }); } }
Token Expiration & Refresh Tokens
Access tokens are short-lived (15 minutes). This limits damage if a token is stolen. Refresh tokens are long-lived (7 days) and stored in httpOnly cookies (JavaScript cannot read them). The refresh token is used to get a new access token without requiring the user to log in again.
const jwt = require('jsonwebtoken'); const accessToken = jwt.sign({ userId: 123 }, 'access_secret', { expiresIn: '15m' }); const refreshToken = jwt.sign({ userId: 123 }, 'refresh_secret', { expiresIn: '7d' }); console.log('Access token (15 minutes)'); console.log('Refresh token (7 days, httpOnly cookie)'); // Later: refreshing the access token function refreshAccess(refreshToken) { try { const decoded = jwt.verify(refreshToken, 'refresh_secret'); const newAccessToken = jwt.sign({ userId: decoded.userId }, 'access_secret', { expiresIn: '15m' }); return { newAccessToken }; } catch (err) { return { error: 'Invalid refresh token' }; } }
Security Best Practices
Never store JWTs in localStorage or sessionStorage. If an attacker injects a script (XSS), they can read localStorage and steal the token. Instead, store refresh tokens in httpOnly cookies (JavaScript cannot read them) and access tokens in memory (state variable).
Knowledge Check
Ready to test your understanding of 9. JWT (JSON Web Tokens)?