Lesson 7 of 17
24. APIs and Idempotency

24.6 How does API auth work, in one page?

3 min read+10 XP

At the machine: Customers pay with their own card. The vendor who restocks the machine uses a staff key. Lose your card, and you cancel it; you don't change every lock in the station.

In the system: Two questions: who is calling (authentication) and what are they allowed to do (authorisation).

API keys identify a program (a partner's server, a script):

  • A long random secret sent in a header: Authorization: Bearer sk_live_....
  • Store only a hash of the key, like a password, and compare in constant time. In the chapter's code, keys are stored as SHA-256 hashes and checked with hmac.compare_digest.
  • Give keys prefixes (sk_live_, sk_test_) so leaked ones are easy to spot, scopes (read-only vs full), and make them easy to rotate and revoke.
  • Server-to-server only: never ship a secret key inside a mobile app or web page.

Tokens identify a user (or a user acting through an app):

  • The user logs in; the auth server issues a short-lived access token, often a signed JWT carrying the user ID, scopes and expiry, plus a longer-lived refresh token.
  • Each request carries Authorization: Bearer <access token>; the API checks the signature and expiry without a database lookup.
  • OAuth 2.0 is the standard for letting a third-party app act for a user with limited permissions ("this app can read your orders, not pay").

Always:

  • HTTPS everywhere; credentials over plain HTTP are stolen credentials.
  • Authorise every request against the specific resource: user 7 may read order 881 only if it's theirs. Missing this check is one of the most common API security bugs.
  • Combine with rate limits per key or user (Chapter 25).

Memory code: "Keys for programs, tokens for people, and check every door, not just the front gate."