FresherTechnicalAuthentication & security
When should an API return 401 and when 403?
Try answering first
Model answer
401 Unauthorized means the request lacks valid authentication: no credentials, an expired token, a bad signature. The status name is misleading, because it is about identity, not permission. The response should include a WWW-Authenticate header naming the scheme, such as Bearer, and the client can retry after logging in or refreshing.
403 Forbidden means the server knows who you are, but you are not allowed to do this. Logging in again will not help.
no token -> 401
expired token -> 401
valid token, wrong role -> 403
valid token, not owner -> 403 (or 404)
Subtleties:
- Return 404 for objects the caller may not even know exist, to avoid confirming that a resource is there. Pick one convention and apply it consistently.
- Use 400/422 for invalid input and 429 for rate limits, so each error code means one thing.
- Keep messages generic. Do not reveal whether a username exists or which permission was missing.
Takeaway: 401 asks "who are you?", 403 answers "I know you, and no".
Key points
- 401 means missing or invalid authentication
- 403 means authenticated but not allowed
- 401 should carry a WWW-Authenticate header
- 404 can hide the existence of an object
Likely follow-ups
- Why might you return 404 instead of 403 for another user's resource?
- Which status do you return for an expired token versus a revoked one?
Common mistakes
- Returning 401 for a user who lacks permission
- Returning 200 with an error message in the body