3 Hours

4. JWT Authentication Fundamentals

JWT Fundamentals

JSON Web Tokens (JWT) are the industry standard for stateless authentication. Unlike session-based authentication, JWTs contain all necessary user information within the token itself, allowing your API to scale horizontally without shared session storage.

What is a JWT?

A JWT is three strings separated by dots. Each part has a specific purpose.

Text
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjMiLCJuYW1lIjoiQWxpY2UifQ.signature
      Header                    Payload                Signature

Header:    Contains the algorithm (HS256)
Payload:   Contains your data (user ID, name, expiration)
Signature: Cryptographic proof the token hasn't been tampered with
Important: JWT is NOT encrypted! The payload is base64 encoded, NOT encrypted. Anyone can decode and read it. Never put sensitive information like passwords in a JWT.

What's Inside a JWT? (Try It)

You can decode a JWT to see what's inside. Here is a simple example.

JavaScript
// Decoding a JWT (no verification, just viewing)
const jwt = require('jsonwebtoken');

const token = jwt.sign({ userId: 123, name: 'Alice' }, 'secret');
console.log('Token:', token);

// Anyone can decode and read the payload
const decoded = jwt.decode(token);
console.log('Payload:', decoded);  // { userId: 123, name: 'Alice', iat: 1234567890 }
Try it: Copy any JWT and paste it into jwt.io. You can see the payload instantly. Never put secrets in a JWT.

Generating a JWT

To generate a JWT, you need a secret key. Keep this key secret — anyone with it can forge tokens.

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

const payload = { userId: 123, role: 'admin' };

const token = jwt.sign(payload, SECRET_KEY, { expiresIn: '1h' });
console.log('Token:', token);
Secret Key Security: Use a strong secret (32+ random characters). Store it in environment variables, never in code.

Verifying a JWT

When you receive a token, you must verify it to ensure it hasn't been tampered with or expired.

JavaScript
function verifyToken(token) {
    try {
        const decoded = jwt.verify(token, SECRET_KEY);
        console.log('Valid! User ID:', decoded.userId);
        return decoded;
    } catch (error) {
        if (error.name === 'TokenExpiredError') {
            console.log('Token has expired');
        } else {
            console.log('Invalid token:', error.message);
        }
        return null;
    }
}

// Example with an expired token
const expiredToken = jwt.sign({ userId: 123 }, SECRET_KEY, { expiresIn: '1ms' });
setTimeout(() => verifyToken(expiredToken), 10);
Always wrap jwt.verify in try/catch! Invalid or expired tokens throw errors that will crash your app if uncaught.

Complete JWT Authentication Flow

Text
1. User logs in with email/password
2. Server validates credentials
3. Server generates JWT: jwt.sign({ userId: 123 }, SECRET, { expiresIn: '1h' })
4. Server returns token to client
5. Client stores token (memory or localStorage)
6. Client sends token in Authorization header: Bearer <token>
7. Server verifies token on every request
8. If valid, server processes request
JavaScript
// Login endpoint
app.post('/login', async (req, res) => {
    const { email, password } = req.body;
    const user = await authenticateUser(email, password);

    if (!user) {
        return res.status(401).json({ error: 'Invalid credentials' });
    }

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

// Protected endpoint
app.get('/profile', (req, res) => {
    const authHeader = req.headers.authorization;
    const token = authHeader?.split(' ')[1];

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

    try {
        const decoded = jwt.verify(token, SECRET_KEY);
        res.json({ userId: decoded.userId, role: decoded.role });
    } catch (error) {
        res.status(401).json({ error: 'Invalid token' });
    }
});

Where to Store JWTs on the Client?

Text
localStorage: Vulnerable to XSS (any JavaScript can read it)
sessionStorage: Also vulnerable to XSS
httpOnly cookie: Not accessible to JavaScript, immune to XSS
Memory (state variable): Most secure but lost on page refresh

Best practice for web apps:
- Access token: Store in memory
- Refresh token: Store in httpOnly cookie
Never store tokens in localStorage! Any script injected via XSS can steal them. Use httpOnly cookies for refresh tokens and memory for access tokens.

Knowledge Check

Ready to test your understanding of 4. JWT Authentication Fundamentals?

Back