How do you implement API key management?
Authentication: proving who is calling
Authentication asks who you are and authorization asks what you may do. Authentication methods differ mainly in where the identity state lives.
For this question · chapter 4 of 4
A key names an application
- OAuth acts for a user. An API key is for an application instead, with no user involved. The app stores the key. The server stores only the key's sha256 hash, 4c7a1d, beside the key's scope and a use count of 0.
- Someone copies the api_keys table out, but every row in that copy is a hash, not a key. A request that presents 4c7a1d, one of those hashes, as its key gets a 401 from the server. A leaked key table gives no access. That protection is the reason we store only the hash.
- The server returns 200 for a GET to /invoices when key k1 is in the X-Api-Key header. The server counts that call, so k1's use count becomes 1. The server refuses a POST to /invoices with the same key and returns 403, because k1's scope is invoices:read, which only allows reading. Keys go in a header, not in the URL, because proxies and logs keep URLs.
- Key rotation needs an overlap, so you create a second key, k2, and show it once. Both keys work for a while. The app switches to k2, so the number of k1 uses in the last hour drops to 0. Retire k1 then, because that count proves nothing uses k1 anymore.
OAuth acts for a user. An API key is for an application instead, with no user involved. The app stores the key. The server stores only the key's sha256 hash, 4c7a1d, beside the key's scope and a use count of 0.
So authentication asks who you are. Authorization asks what you may do. The methods differ mainly in where you keep the identity state. That state can be in your own store, in the token itself, or in a hashed key row.
© LearnThatStack - diagrams may not be republished without permission.
Want a quick review of the fundamentals? See the API Design cheatsheet.
74 of 92 API Design answers are in Pro.
Full answers, code samples, and AI explanations that go simpler or deeper. Cancel anytime.
- Full answers + code
- AI explanations, simpler or deeper
- 1,000 AI credits / month
- Cancel anytime