Verifies JWT access tokens and attaches authenticated user information to the Express
request object. This middleware extracts Bearer tokens from the Authorization header,
validates them against the JWT secret, and populates req.user with the decoded payload.
The middleware handles various JWT validation scenarios including missing tokens,
invalid tokens, expired tokens, and configuration errors. All authentication failures
are logged for security monitoring and result in appropriate HTTP error responses.
This middleware is used extensively across protected routes in authentication,
user management, and content management endpoints. It serves as the foundation
for all authenticated operations in the application.
// Chain with other middleware for complex authorization router.put('/users/:id/role', authenticateToken, requireRole('admin'), userController.updateUserRole );
Example
// Access user information in route handler constprotectedHandler = (req: Request, res: Response) => { constuserId = req.user?.sub; // Available after authenticateToken constuserRole = req.user?.role; // ... handle authenticated request };
JWT Authentication Middleware
Verifies JWT access tokens and attaches authenticated user information to the Express request object. This middleware extracts Bearer tokens from the Authorization header, validates them against the JWT secret, and populates req.user with the decoded payload.
The middleware handles various JWT validation scenarios including missing tokens, invalid tokens, expired tokens, and configuration errors. All authentication failures are logged for security monitoring and result in appropriate HTTP error responses.
This middleware is used extensively across protected routes in authentication, user management, and content management endpoints. It serves as the foundation for all authenticated operations in the application.