Authorization (what are you allowed to do?)
Authorization runs after login and decides what the user may access. Broken Access Control is #1 in the OWASP Top 10.
Common attacks
- IDOR: change
/orders/101to/orders/102and read someone else's order - Privilege escalation: a normal user calls an admin endpoint
- Mass assignment: send
{ "role": "admin" }in a profile update - Hidden UI = security? Hiding a button does not protect the API behind it
Packages
| Package | Use |
|---|---|
casl (@casl/ability) | Attribute-based permissions (can user X update post Y?) |
accesscontrol | Role-based access control (RBAC) |
uuid | Unguessable IDs (helps, but is not a replacement for checks) |
❌ Vulnerable
app.get('/orders/:id', requireAuth, async (req, res) => {
res.json(await Order.findById(req.params.id)); // no ownership check → IDOR
});
app.put('/me', requireAuth, async (req, res) => {
await User.updateOne({ _id: req.user.id }, req.body); // mass assignment → role: "admin"
});✅ Secure
// Ownership check inside the query
app.get('/orders/:id', requireAuth, async (req, res) => {
const order = await Order.findOne({ _id: req.params.id, userId: req.user.id });
if (!order) return res.status(404).end(); // 404, not 403: don't reveal it exists
res.json(order);
});
// Allowlist the fields a user may change
app.put('/me', requireAuth, async (req, res) => {
const { name, avatar } = req.body;
await User.updateOne({ _id: req.user.id }, { name, avatar });
res.status(204).end();
});
// Role middleware
const requireRole = (...roles) => (req, res, next) =>
roles.includes(req.user.role) ? next() : res.status(403).json({ error: 'Forbidden' });
app.delete('/users/:id', requireAuth, requireRole('admin'), deleteUser);Checklist
- Deny by default; allow explicitly
- Check ownership on every request that takes an ID
- Check permissions on the server, never only in the UI
- Allowlist writable fields (no
req.bodypassed straight to the DB) - Keep authorization logic in one place (middleware/policy), not copied per route
- Write tests: "user A cannot access user B's resource"