JWT Authentication Middleware

mediumTypeScript

Lesson

JWT Authentication in Express Applications

JSON Web Tokens (JWT) provide a secure way to transmit information between parties as a JSON object. In web applications, JWTs are commonly used for authentication - allowing servers to verify user identity without maintaining session state.

A JWT consists of three parts separated by dots: header.payload.signature. The header specifies the algorithm used, the payload contains claims (user data), and the signature ensures the token hasn't been tampered with. When a user logs in with valid credentials, the server creates a JWT containing user information and signs it with a secret key.

The key advantage of JWTs is that they're stateless - all necessary information is contained within the token itself. This makes them perfect for distributed systems and APIs where you don't want to maintain server-side sessions.

In Express applications, JWT authentication typically follows this pattern:

  1. Login Route: Validates user credentials and returns a signed JWT
  2. Authentication Middleware: Extracts and verifies JWTs from request headers
  3. Protected Routes: Use the middleware to ensure only authenticated users can access them

The standard practice is to send JWTs in the Authorization header using the Bearer scheme: Authorization: Bearer <token>. Your middleware extracts this token, verifies it using the same secret key used for signing, and either grants access or returns an authentication error.

Example
1import jwt from 'jsonwebtoken'; 2 3// Creating a JWT when user logs in 4const createToken = (userData: any) => { 5 return jwt.sign( 6 { id: userData.id, email: userData.email }, 7 'secret-key', 8 { expiresIn: '24h' } 9 ); 10}; 11 12// Middleware to verify JWT tokens 13const verifyToken = (req: any, res: any, next: any) => { 14 const token = req.headers.authorization?.split(' ')[1]; 15 16 if (!token) { 17 return res.status(401).json({ error: 'No token provided' }); 18 } 19 20 try { 21 const decoded = jwt.verify(token, 'secret-key'); 22 req.user = decoded; 23 next(); 24 } catch (error) { 25 res.status(401).json({ error: 'Invalid token' }); 26 } 27};
L4Sign token with user data, secret key, and expiration time
L12Extract Bearer token from Authorization header
L19Verify token and attach user data to request object

Key Takeaways

  • •JWTs are stateless tokens that contain encoded user information and a signature for verification
  • •Authentication middleware should extract tokens from headers, verify them, and either grant access or return 401
  • •Always use strong secret keys and set appropriate expiration times for security
Loading...