2.5 Hours

9. JWT (JSON Web Tokens)

Authentication

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.

JavaScript
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

JSON Web Token (JWT) Anatomy & Verification Three Base64Url components cryptographically bound by HMAC-SHA256 signature 1. HEADER Algorithm & Token Type {"alg": "HS256", "typ": "JWT"} eyJhbGciOiJIUzI1... 2. PAYLOAD User Claims & Expiry {"sub": "usr_99", "role": "admin"} eyJzdWIiOiJ1c3Jf... 3. SIGNATURE HMACSHA256 Hash HMACSHA256( header + payload, secret) TJVA95OrM7E2cBab... ✓ Tamper-proof: Modifying even 1 bit of payload invalidates the signature instantly

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.

JavaScript
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.

JavaScript
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().

JavaScript
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.

JavaScript
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).

Remember: The JWT payload is base64 encoded, NOT encrypted. Anyone can decode and read it. Never put passwords or other secrets in the payload.

Knowledge Check

Ready to test your understanding of 9. JWT (JSON Web Tokens)?

Back