Loading content…
Loading content…
Create an Express authentication middleware that validates JWT tokens. The middleware must inspect the `Authorization` header, parse Bearer tokens, check signatures, append user objects to requests, and block unauthorized traffic with a 401 status code.
Expected Output
An Express middleware function `authenticateToken(req, res, next)`.
Click to toggle the recommended code solution
Architectural Explanation
The middleware checks authorization headers, validates JWT token signatures against secret keys, and calls next() to pass control to the route handler on success.Code Snippet
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
export interface AuthenticatedRequest extends Request {
user?: any;
}
export function authenticateToken(
req: AuthenticatedRequest,
res: Response,
next: NextFunction
) {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (!token) {
return res.status(401).json({ error: "Access token is missing." });
}
jwt.verify(token, process.env.JWT_SECRET || "fallback-secret", (err, decoded) => {
if (err) {
return res.status(403).json({ error: "Token signature is invalid." });
}
req.user = decoded;
next();
});
}How to pitch this solution during technical interviews
I authorize endpoints using Express middlewares. I parse authorization headers, isolate tokens, and verify signatures using JWT libraries. I mount decoded variables onto requests, and block requests with a 401 status if verification fails.