Authorization Middleware
Authentication tells you who the user is. Authorization decides what they may do. Keeping the two in separate middleware makes routes read like a policy:
app.delete('/posts/:id', authenticate, requireRole('editor'), deletePost);Three common models
| Model | Question it answers | Example |
|---|---|---|
| Role-based (RBAC) | does the user have role X? | only admin may delete users |
| Permission-based | does the user have permission posts:delete? |
roles map to fine-grained permissions |
| Ownership / attribute-based | does the user own this resource? | authors may edit their own posts |
Real apps combine them: "editors may edit any post; authors may edit their own; everyone may read".
Role checks with a middleware factory
To keep the example focused, a fake authenticate reads the user from an X-User header (in real code this comes from the token, as in the previous lesson):
const express = require('express');
const users = {
ana: { id: 'ana', roles: ['admin'] },
bo: { id: 'bo', roles: ['editor'] },
cy: { id: 'cy', roles: [] },
};
function authenticate(req, res, next) {
req.user = users[req.get('X-User')];
if (!req.user) return res.status(401).json({ error: 'Not authenticated' });
next();
}
function requireRole(...allowed) {
return (req, res, next) => {
if (!req.user.roles.some((r) => allowed.includes(r))) {
return res.status(403).json({ error: `Requires role: ${allowed.join(' or ')}` });
}
next();
};
}
const app = express();
app.get('/reports', authenticate, requireRole('admin', 'editor'), (req, res) => res.json({ ok: 'reports' }));
app.delete('/users/:id', authenticate, requireRole('admin'), (req, res) => res.json({ deleted: req.params.id }));
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const tries = [
['GET', '/reports', undefined],
['GET', '/reports', 'cy'],
['GET', '/reports', 'bo'],
['DELETE', '/users/7', 'bo'],
['DELETE', '/users/7', 'ana'],
];
for (const [method, path, who] of tries) {
const res = await fetch(base + path, { method, headers: who ? { 'X-User': who } : {} });
console.log(`${(who ?? 'anon').padEnd(4)} ${method} ${path}`.padEnd(24), res.status, await res.text());
}
server.close();
});anon GET /reports 401 {"error":"Not authenticated"}
cy GET /reports 403 {"error":"Requires role: admin or editor"}
bo GET /reports 200 {"ok":"reports"}
bo DELETE /users/7 403 {"error":"Requires role: admin"}
ana DELETE /users/7 200 {"deleted":"7"}
Permissions instead of roles
Hard-coding role names in routes gets messy when roles change. Map roles to permissions in one place, and check permissions in the routes:
type Permission = 'posts:read' | 'posts:write' | 'posts:delete' | 'users:manage';
const ROLE_PERMISSIONS: Record<string, Permission[]> = {
reader: ['posts:read'],
author: ['posts:read', 'posts:write'],
editor: ['posts:read', 'posts:write', 'posts:delete'],
admin: ['posts:read', 'posts:write', 'posts:delete', 'users:manage'],
};
function can(roles: string[], permission: Permission): boolean {
return roles.some((role) => ROLE_PERMISSIONS[role]?.includes(permission) ?? false);
}
const checks: [string[], Permission][] = [
[['reader'], 'posts:write'],
[['author'], 'posts:write'],
[['author', 'editor'], 'posts:delete'],
[['editor'], 'users:manage'],
[['unknown-role'], 'posts:read'],
];
for (const [roles, perm] of checks) {
console.log(`${roles.join('+').padEnd(13)} ${perm.padEnd(13)} ${can(roles, perm)}`);
}reader posts:write false
author posts:write true
author+editor posts:delete true
editor users:manage false
unknown-role posts:read false
Unknown roles get no permissions — authorization must fail closed.
Ownership checks
Roles can't express "only your own post". That check needs the resource, so it usually lives in the handler (or a middleware that loads the resource first):
const express = require('express');
const posts = new Map([
[1, { id: 1, authorId: 'bo', title: 'Hello' }],
[2, { id: 2, authorId: 'cy', title: 'World' }],
]);
const app = express();
app.use(express.json());
app.use((req, res, next) => { // fake authentication
req.user = { id: req.get('X-User'), roles: req.get('X-User') === 'ana' ? ['editor'] : ['author'] };
next();
});
function loadPost(req, res, next) {
req.post = posts.get(Number(req.params.id));
if (!req.post) return res.status(404).json({ error: 'Post not found' });
next();
}
function canEditPost(req, res, next) {
const isOwner = req.post.authorId === req.user.id;
const isEditor = req.user.roles.includes('editor');
if (!isOwner && !isEditor) return res.status(403).json({ error: 'You can only edit your own posts' });
next();
}
app.patch('/posts/:id', loadPost, canEditPost, (req, res) => {
req.post.title = req.body.title;
res.json(req.post);
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const edit = async (who, id, title) => {
const res = await fetch(`${base}/posts/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json', 'X-User': who },
body: JSON.stringify({ title }),
});
console.log(`${who} edits post ${id}:`, res.status, await res.text());
};
await edit('bo', 1, 'Hello, again');
await edit('bo', 2, 'Hijacked');
await edit('ana', 2, 'Edited by editor');
await edit('bo', 9, 'Nope');
server.close();
});bo edits post 1: 200 {"id":1,"authorId":"bo","title":"Hello, again"}
bo edits post 2: 403 {"error":"You can only edit your own posts"}
ana edits post 2: 200 {"id":2,"authorId":"cy","title":"Edited by editor"}
bo edits post 9: 404 {"error":"Post not found"}
Tip: Some APIs answer 404 instead of 403 when a user requests another user's private resource, so they don't even reveal that it exists. Choose one policy and apply it consistently.
Rules of thumb
| Rule | Why |
|---|---|
| authorize on the server, every time | hiding a button in the UI is not security |
| deny by default | a forgotten check should block, not allow |
| check ownership with ids from the token, never from the body | req.body.userId can be anything |
| filter list endpoints too | GET /orders must return only the caller's orders |
Test yourself
A user is logged in but lacks the required role. Which status should the API return?
- 400
- 401
- 403
- 500
Where should an 'only edit your own post' rule be checked?
- In the frontend only
- In a check that compares the loaded post's owner with the authenticated user id
- In the CORS middleware
- In
express.json()
What should a permission check do for a role it doesn't recognise?
- Allow everything
- Deny (fail closed)
- Throw a 500 error
- Treat it as admin