Preparing your workspace
Authentication verifies who a user is, while authorization determines what that authenticated user is allowed to do.
Protected APIs usually need middleware that identifies the current user before the request reaches sensitive routes. After authentication, authorization checks can determine whether the user has the required role or permission. Keeping these checks in middleware avoids repeating the same logic in every controller. Authentication should use secure mechanisms appropriate for the application, and authorization should always be enforced on the server rather than trusting frontend controls.
An education platform may allow students to view their courses, mentors to manage assigned students, and admins to manage platform settings.
function requireRole(requiredRole) {
return (req, res, next) => {
if (!req.user) {
return res.status(401).json({ error: 'Authentication required' });
}
if (req.user.role !== requiredRole) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
};
}
app.get('/admin/settings', requireRole('admin'), (req, res) => {
res.json({ message: 'Admin settings' });
});Only an authenticated user with the required admin role can access the protected route.