Card 01/ 12
Authentication and Authorisation
One question is who is calling; the other is what that caller may do, and an API must answer both.
Authentication establishes who is calling, by checking a credential such as a key, a token or a certificate. Authorisation decides whether that caller may perform this request on this resource. An API runs them in that order, because permission cannot be checked for a caller it has not identified, and each failure has its own status code: 401 when the caller is not authenticated, 403 when it is authenticated but not allowed.
When No credential, or one that is invalid or expired
, choose401 Unauthorized, with a WWW-Authenticate header saying how to authenticate
When A valid credential, but the caller lacks permission for this action or resource
, choose403 Forbidden, or 404 when even confirming the resource exists would leak information
When A valid credential, and the caller has permission
, chooseThe request proceeds
Authentication answers "who are you?" with proof. A username alone is a claim; a password, a signed token or a private key is proof. The result is an identity the rest of the request can use, such as a user id or a client id.
Authorisation answers "may you do this?" from that identity. It can be broad, such as a role that may read all orders, or precise, such as the rule that a customer may read only their own orders. The precise rules are where most API breaches happen, covered in the topic on protecting an API.
Why the order matters. Checking permission first would mean reasoning about a caller the API cannot vouch for. Checking identity and stopping there means any authenticated user may do anything.
The names are misleading. The 401 status is called Unauthorized but means unauthenticated. The abbreviations help: authn for authentication, authz for authorisation.
So every protected endpoint needs both checks, identity first and permission second, and each failure returns its own code.
← → move through sections and cards