Role Authorization Middleware Chain
Enforce least-privilege access with composable role middleware that verifies tokens, resolves roles, and gates routes without inline checks.
Code
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:
expressandjsonwebtokenare a real dependency, resolved by the package manager. - The guard
!tokenshort-circuits the flow with an earlyreturnwhen 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
JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.OAuth 2.0 PKCE Code GeneratorGenerate RFC 7636 OAuth 2.0 PKCE code verifiers with Web Crypto CSPRNG, compute SHA-256 code challenges, and build full authorization URLs.
FAQ
- Does this require external packages?
- Yes — `express` and `jsonwebtoken`. Add them to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.