Part 09 / Topic 3 of 7
Authentication
For an internal customer-facing service, an API key per consuming team (sent as a header) is usually right-sized: easy to issue, easy to rotate, easy to revoke one team without touching another. The implementation details that matter:
- Compare with
hmac.compare_digest, exactly as with webhook signatures (Part 5): a plain==leaks match-length through response timing. The rule generalises: any secret comparison is constant-time. - Missing key is a 401, not a 422. The example defaults the header to
""so FastAPI does not reject the request as malformed before your auth code can answer properly. - Keys live in config (next part), never in source.
🧪 Quick quiz
- Why check API keys with
hmac.compare_digestinstead of==?
Show the answer
Constant-time comparison avoids leaking information through response timing. The same rule applies to tokens, keys and signatures.
Done here? The practice set for Part 9 — 4 exercises with solutions — is on the part page.