

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Authentication
incomplete
2: Stateless vs. Stateful Authentication
incomplete
3: What Are Sessions?
incomplete
4: What Are Cookies?
incomplete
5: Cookie Security
incomplete
6: Session Lifetime
incomplete
7: Password Resets
incomplete
8: Broken Password Reset Flow
incomplete
9: OAuth 2.0
incomplete
10: SAML and OIDC
incomplete
11: API Keys
incomplete
12: Reauthentication
incomplete
13: Authentication Misconceptions
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
API keys are often used to authenticate programmatic requests. They're not user sessions or OAuth tokens: they're often long-lived bearer credentials, which makes them very dangerous if leaked.
Just imagine how much you could run up my Claude bill if you had my API key...
.env filesKeys must be cryptographically random and long enough to resist guessing. Thirty-two random bytes (256 bits) is a strong default.
// unsafe: predictable pattern
const apiKey = `${userId}-${Date.now()}`;
// safer: cryptographically random
import { randomBytes } from "node:crypto";
const apiKey = randomBytes(32).toString("hex");
Never generate keys from user data, timestamps, or anything predictable, just use a secure random generator.
If your service only needs to verify incoming keys, store a hash of each high-entropy key rather than the plaintext.
import { hash } from "node:crypto";
function hashApiKey(apiKey: string): string {
return hash("sha256", apiKey, "hex");
}
Generate the raw key, display it once, and then store its hash. That way if an attacker secretly gains read-access to your database, they won't have the plaintext keys to use.
Rotate keys:
If a key is compromised, revoke it immediately, notify the owner, and investigate the incident.
Treat API keys like passwords: transmit them only over HTTPS, keep them out of URLs and logs, and make revocation easy.
Bearly Secure has a small machine-to-machine endpoint for a warehouse integration, but anyone can currently call it. The route should authenticate requests with an API key in the X-API-Key header.
Require a valid warehouse API key on the existing orders endpoint.
With Bearly Secure still running, run and submit the CLI tests from the project root.