Menu

How to store API keys safely in FastAPI (and why bcrypt is the wrong tool)
📰

How to store API keys safely in FastAPI (and why bcrypt is the wrong tool)

DEV Community: python·AutoIncome·about 7 hours ago
#bv2Is6Lt
#devtopython#devto#dev#fastapi#import
Long article (794 words) — no AI summary yet.
Reading 0:00
15s threshold

This article was created with the help of AI. The code was run and checked before publishing (FastAPI 0.165.0, SQLAlchemy 2.1.9).

You want scripts and bots to call your FastAPI app with an X-API-Key header. Two questions come up quickly: how do I store the key, and should I hash it with bcrypt like a password?

Short answer: generate a long random key, store only its SHA-256 hash, and look the key up by that hash.

Why not bcrypt?

Slow, salted hashes protect secrets that people choose, because people choose guessable ones. The Python docs say passwords "should be salted and hashed using a cryptographically strong one-way (irreversible) hash function" [1].

A generated key is different. The same docs say 32 bytes (256 bits) of randomness is believed to be sufficient for typical uses [1].…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.