
Module 1: JWT Fundamentals & Architecture - The Theoretical Backbone
What is JWT? Explanation of JSON Web Tokens as an open, industry-standard RFC 7519 method for representing claims securely between two parties.
Structure (Header, Payload, Signature): 1 1. github.com
Symmetric vs Asymmetric Signing:
Use Cases of JWT:
Comparison with Sessions and Cookies:
Common Mistakes:
Enterprise Best Practices:
Hands-on: Explore the structure of a JWT using online decoders (e.g., jwt.io). Generate simple JWTs with different payloads and signing algorithms to observe the structure.
Module 2: Setting Up JWT in Node.js (Express) - Practical Implementation
Signing and Verifying JWTs: Using the jsonwebtoken library in Node.js.JavaScript
// Installation: npm install jsonwebtoken
const jwt = require('jsonwebtoken');
const secretKey = 'your-secret-key'; // In production, use a strong, environment-variable-based secret
// Signing a JWT
const userPayload = { userId: 123, username: 'testuser' };
const accessToken = jwt.sign(userPayload, secretKey, { expiresIn: '1h' });
console.log('Generated Access Token:', accessToken);
// Verifying a JWT
jwt.verify(accessToken, secretKey, (err, decoded) => {
if (err) {
console.error('Token verification failed:', err);
} else {
console.log('Decoded Token:', decoded);
}
});
Creating a Secure Login Route: Implementing a route (e.g., /login) that accepts user credentials, authenticates them (e.g., against a database), and returns a JWT upon successful authentication.JavaScript
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const app = express();
const users = [{ id: 1, username: 'testuser', password: await bcrypt.hash('password123', 10) }]; // In real app, fetch from DB
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(401).json({ message: 'Invalid credentials' });
}
const accessToken = jwt.sign({ userId: user.id, username: user.username }, 'your-secret-key', { expiresIn: '1h' });
res.json({ accessToken });
});
Protecting Routes using Middleware (Auth Guards): Creating middleware to verify the JWT in the Authorization header of incoming requests and allow access to protected routes only if the token is valid.JavaScript
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, 'your-secret-key', (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
};
app.get('/protected', authenticateToken, (req, res) => {
res.json({ message: 'This route is protected', user: req.user });
});
Handling Token Expiration and Renewal: Implementing logic to handle expired tokens (typically returning a 401 Unauthorized error) and setting up a mechanism for token renewal (often using refresh tokens, covered in the next module).
Common Mistakes:
Enterprise Best Practices:
express-jwt for simplified JWT authentication in Express.Hands-on: Set up a basic Express.js application with a login route that issues a JWT and a protected route that requires a valid JWT for access. Test this using Postman.
Module 3: Access Token vs Refresh Token Architecture - Enhancing Security and User Experience