Protect User API Endpoints
Now apply authentication middleware to endpoints that require a logged-in user.
For example:
- Viewing all users requires an administrator.
- Viewing a profile requires authentication and ownership or administrator permission.
- Updating a profile requires authentication and ownership or administrator permission.
- Deleting a user requires administrator permission.
We will introduce role authorization in the next section.
The create account and login endpoints remain public.
Protect User Routes
import { authenticate } from '../middleware/auth.middleware.js';
router.get('/', authenticate, getAllUsers);
router.get('/:id', authenticate, getUserById);
router.put('/:id', authenticate, updateUser);
router.patch('/:id', authenticate, updateUser);
router.delete('/:id', authenticate, deleteUser);Adds authentication middleware to the user management endpoints.
Key Takeaways
Public and protected endpoints should be separated.
Authentication middleware executes before controllers.
Authentication alone does not establish resource ownership.