javascript Authentication

JWT Authentication Middleware

Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded user to the request object.

Apex Logic 0 copies
javascript
const jwt = require('jsonwebtoken');

const authenticate = (req, res, next) => {
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return res.status(401).json({ error: 'No token provided' });
    }

    const token = authHeader.split(' ')[1];
    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = decoded;
        next();
    } catch (err) {
        if (err.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token expired' });
        }
        return res.status(403).json({ error: 'Invalid token' });
    }
};

const authorize = (...roles) => {
    return (req, res, next) => {
        if (!req.user || !roles.includes(req.user.role)) {
            return res.status(403).json({ error: 'Insufficient permissions' });
        }
        next();
    };
};

module.exports = { authenticate, authorize };

Tags

jwt express middleware auth

Related Snippets

javascript

MongoDB Connection with Retry

javascript

Express Global Error Handler

javascript

Rate Limiter with Sliding Window

javascript

File Upload Handler with Validation