Card 04/ 09
401 vs 403
401 means "we do not know who you are", and 403 means "we know, and the answer is no".
401 Unauthorized means the request carried no valid credentials, so the server does not know who is calling. 403 Forbidden means the server knows exactly who is calling and that caller is not allowed to do this. The names mislead: 401 is about authentication, proving who you are, and 403 about authorisation, what you may do.
When No credentials were sent, or the token is expired, malformed or revoked
, choose401 Unauthorized, with a WWW-Authenticate header saying how to authenticate.
When The credentials are valid, but this caller may not perform this action
, choose403 Forbidden.
When The credentials are valid, and the caller should not even learn that the resource exists
, choose404 Not Found.
When The credentials are valid and the action is allowed
, chooseProcess the request.
401 invites another attempt. The client can fix it by signing in again or refreshing its token. The standard requires a WWW-Authenticate header naming the scheme the server expects, for example WWW-Authenticate: Bearer, so the client knows what to send.
403 does not. Signing in again changes nothing, because the server already knows who the caller is. A signed-in user without the admin role calling DELETE /users/7 gets a 403, and the fix is to get the role, not a new token.
When 404 is better. If a user asks for /orders/42 and order 42 belongs to someone else, a 403 confirms that order 42 exists. For private resources, many APIs answer 404 so that ids cannot be probed. Choose one rule for the whole API and apply it everywhere.
The rule for choosing. Ask whether the server knows who is calling. If not, 401. If it does and the answer is no, 403, or 404 when existence itself is private.
← → move through sections and cards