Card 01/ 12

ConceptDifficulty: Beginner2 min

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.

What does the API answer to this request?
  1. When No credential, or one that is invalid or expired

    , choose

    401 Unauthorized, with a WWW-Authenticate header saying how to authenticate

  2. When A valid credential, but the caller lacks permission for this action or resource

    , choose

    403 Forbidden, or 404 when even confirming the resource exists would leak information

  3. When A valid credential, and the caller has permission

    , choose

    The 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.