What is the difference between 401 and 403?
401 Unauthorized means not authenticated (no token or invalid token). 403 Forbidden means authenticated but not authorized (wrong role or permission). Check auth first, then authorization.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Role-Based Access Control (RBAC) in Node.js
Add a role field on the user. Write an auth middleware that verifies the JWT and sets req.user. Write a requireRole factory that checks req.user.role. Apply to routes: router.use('/admin', auth, requireRole('admin')). Check resource ownership for user-specific resources.
Store permissions on the user (array of strings like 'post:delete', 'user:ban'). Write a requirePermission factory that checks req.user.permissions.includes(perm). More flexible than roles but harder to manage at scale.
In the handler, compare req.user.userId to the resource's owner. If they do not match and the user is not an admin, return 403. Example: if (req.user.role !== 'admin' && req.user.userId !== req.params.id) return res.status(403).
Still have questions?
Browse all our FAQs or reach out to our support team
