Authentication & Security
Node.js Role Based Authorization
Authorisation decides what an authenticated user may do. The usual implementation is a role on the user record plus middleware that checks it before the handler runs.
What is Role Based Authorization in Node.js?
Authorisation decides what an authenticated user may do. The usual implementation is a role on the user record plus middleware that checks it before the handler runs.
Role Based Authorization example
JavaScript
export const requireRole = (...roles) => (req, res, next) => {
if (!req.user) return res.status(401).json({ error: 'Not authenticated' });
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Not allowed' });
}
next();
};
app.delete('/api/jobs/:id', requireAuth, requireRole('admin', 'employer'), deleteJob);
// ownership check inside the handler
async function deleteJob(req, res) {
const job = await Job.findById(req.params.id);
if (!job) return res.status(404).json({ error: 'Job not found' });
if (req.user.role !== 'admin' && String(job.postedBy) !== req.user.sub) {
return res.status(403).json({ error: 'Not allowed' });
}
await job.deleteOne();
res.status(204).end();
}Key points to remember
- Role checks are not enough — also verify the user owns the specific record.
- Broken object-level authorisation is the most common API vulnerability in the wild.
- Deny by default: require an explicit rule to allow, not to block.
Common mistakes with Role Based Authorization
- Checking the role but not the record owner, so any employer can delete any job.
- Trusting a role sent by the client rather than reading it from the verified token.
Node.js Role Based Authorization— Interview Questions & FAQs
What is broken object level authorization?+
When an endpoint checks that a user is logged in but not that the specific record belongs to them, so changing an id in the URL exposes someone else’s data. It is consistently the top item in the OWASP API security list.
