Handling requests safely · mid
Authentication and authorization middleware
Authentication middleware turns a session cookie or Bearer token into req.user (or answers 401), and authorization checks that this user may do this action on this specific resource (or answers 403), on every request, on the server.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- authenticate: read the credential (Authorization: Bearer ... or a session cookie), verify it (signature, expiry, issuer and audience for a JWT; a store lookup for a session), set req.user. Missing or invalid -> 401.
- authorize: role checks (requireRole('admin')) and ownership checks (order.userId === req.user.id). Not allowed -> 403, or 404 when you do not want to reveal that the resource exists.
- Broken Object Level Authorization (BOLA, also called IDOR) is #1 in the OWASP API Security Top 10 (2023): GET /orders/123 must check that order 123 belongs to the caller.
- Never trust a user id from the body or query for 'who am I'. Use req.user.id from the verified credential.
- Deny by default: apply authentication at the router level so new routes are protected, then mark public routes explicitly.
- Keep authorization rules in one place (policy functions) and unit-test them.
The red pen
Common traps: mistake → fix
Mistake: Hiding the button in the UI is authorization
Fix: the API must check every request.
Mistake: A valid token means the user may access any id
Fix: check ownership of the specific object.
Mistake: 401 and 403 mean the same
Fix: 401: we do not know who you are; 403: we know you, and you are not allowed.
Easy to hard
Questions interviewers ask, easy to hard
- How do you protect routes in Express?
- 401 vs 403?
- A user changes /orders/123 to /orders/124 and sees someone else's order. What went wrong, and how do you prevent it everywhere?
- Where does authorization logic live in your codebase?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.