Role Authorization Middleware Chain

Enforce least-privilege access with composable role middleware that verifies tokens, resolves roles, and gates routes without inline checks.

JavascriptNodeSecurity Boundaries

Code

javascriptsnippet
39 lines
import express from 'express';
import jwt from 'jsonwebtoken';

function requireAuthMiddleware(req, res, next) {
  const header = req.headers.authorization ?? '';
  const token = header.startsWith('Bearer ') ? header.slice(7) : null;
  if (!token) return res.status(401).json({ error: 'token required' });
  try {
    req.claims = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    res.status(403).json({ error: 'invalid token' });
  }
}

function requireRoleMiddleware(...allowed) {
  return (req, res, next) => {
    const role = req.claims?.role;
    if (!role || !allowed.includes(role)) {
      return res.status(403).json({ error: 'role ' + role + ' not permitted' });
    }
    next();
  };
}

const app = express();

app.delete('/invoices/:id',
  requireAuthMiddleware,
  requireRoleMiddleware('admin', 'finance'),
  (req, res) => res.json({ deleted: req.params.id }),
);

app.get('/profile',
  requireAuthMiddleware,
  (req, res) => res.json({ userId: req.claims.sub }),
);

app.listen(3000);

How the snippet works

Count the functions requireAuthMiddleware and requireRoleMiddleware as the entire surface area of Role Authorization Middleware Chain.

Configuration comes from the environment — it reads JWT_SECRET, so the same code switches behavior between environments without edits.

What to watch for

  • Plan for an install step: express and jsonwebtoken are a real dependency, resolved by the package manager.
  • The guard !token short-circuits the flow with an early return when its condition holds.

Applying it

Signature: function requireAuthMiddleware(req, res, next)

Statements that matter

return (req, res, next) => {
const role = req.claims?.role;
if (!role || !allowed.includes(role)) {
return res.status(403).json({ error: 'role ' + role + ' not permitted' });
}
next();
};
if (!token) return res.status(401).json({ error: 'token required' });
const header = req.headers.authorization ?? '';

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `express` and `jsonwebtoken`. Add them to your project before running the snippet.