OTP, Secret Keys, API Tokens, and User-Agent Diagnostics for Auth Engineers
Authentication bugs rarely stay small: storing raw merchant API keys cleanly in plain database columns exposes every tenant if a read-replica backup leaks; shipping 6-digit SMS or email OTPs without tight attempt locks leaves 1,000,000-combination codes trivial to brute-force; and brittle User-Agent string checks deny legitimate privacy browsers while missing headless bots.
Getting token generation, OTP throttling, and edge diagnostics right closes these gaps cleanly without complicating login UX.
Designing API Keys Properly: Prefix + Entropy + SHA-256 Storage
Never treat long-lived service API keys like low-friction cookies—or store their plaintext values directly in SQL tables:
- Include an unmistakable non-secret prefix (
swt_live_,whsec_): Adding a distinct vendor prefix allows automated secret-scanning hooks (GitHub Secret Scanning, pre-commit scanners) to catch leaked keys in public repos within seconds, and gives support teams a safe identifier (key_prefix: "swt_live_8a9f") to revoke without ever viewing the full secret. - Generate keys strictly via a CSPRNG (
crypto.getRandomValues,random_bytes): Never concatenate timestamps, database auto-increment IDs, or JavaScriptMath.random()outputs—only cryptographic randomness resists prediction. Generate development test secrets locally via a Secret Key Generator or Random Token Generator. - Store only a fast cryptographic hash (
SHA-256) of high-entropy keys: Unlike human passwords (which require slow memory-hard hashing covered in our password hashing guide), a256-bitCSPRNG API token carries full entropy and cannot be dictionary-guessed. Hashing the submitted bearer token withSHA-256and comparing against the storedtoken_hashcolumn keeps verification sub-millisecond while protecting keys completely if a database snapshot escapes!
Six-Digit OTP and PIN Architecture Without Brute-Force Exposure
Six decimal digits (000000–999999) provide at most 1,000,000 guesses (~20 bits of entropy)—a trivial target for automated requests unless strictly constrained. Whenever issuing transactional codes or testing verification flows using an OTP Generator or PIN Generator:
- Cap verification attempts strictly (
3 to 5 tries max per issued code): Invalidate the active OTP completely after five wrong guesses rather than only rate-limiting per IP address (attackers routinely rotate residential proxy IPs cleanly past per-IP limits). - Keep OTP lifetimes brief (
5 to 10 minutes): Expire stale confirmation codes aggressively, and always invalidate prior active codes the moment a user clicks "Resend code." - Separate OTP storage from predictable seeds and allowlist test fixtures: In automated staging suites, draft deterministic mock tokens carefully via a JWT Generator and JWT Payload Generator alongside verification rules from our JWT security audit guide—never reusing signing secrets across staging and production!
Reading User-Agent, Browser Telemetry, and Input Validation Safely
Use User-Agent for Support Telemetry—Not Security Decisions
Analyzing incoming request strings through a User-Agent Parser or inspecting local runtime capabilities via a Browser Info Checker helps support teams reproduce weird Safari font glitches or isolate broken mobile WebView releases cleanly.
However, do not gate feature logic or trust bots purely on User-Agent strings: clients spoof User-Agent arbitrarily in one header line, and browsers intentionally freeze/reduce minor OS versions to curb fingerprinting (User-Agent Reduction). For UI capabilities, rely on CSS @supports and JS API checks ('share' in navigator), not browser-version if/else chains.
Clean Validation Boundaries for Email & Redirect URLs
- Avoid overly strict email regex traps (
+signs and new TLDs): Rejectingalice+billing@company.cloudfrustrates paying customers; perform basic format sanity checks with an Email Validator and prove real mailbox ownership via actual verification links (token). - Protect external redirect and callback inputs (
Open Redirect&SSRF): Before accepting custom webhook or return destinations, validate syntax strictly via a URL Validator, whitelisthttps://schemes cleanly (blockingjavascript:orfile://payloads), and verify target hosts cannot resolve back into internal loopback or RFC 1918 cloud metadata ranges (169.254.169.254).
Secret Rotation Without Causing Production Outages
Rotating a signing secret (HMAC webhook secret or internal JWT key) by overwriting the environment variable instantly breaks every active user session or webhook event currently in transit! Use an overlapping dual-key rotation window:
- Publish the new signing key alongside the previous key (
kid: "key-2026-11"andkid: "key-2026-08"): Verify incoming requests against both active secrets during the transition window, while issuing new tokens strictly using the fresh key. - Monitor
kidtelemetry until old-key verifications drop to zero: Wait past maximum token/webhook retry TTL (e.g. 24–72 hours) cleanly before retiring the old key permanently. - Bind OTP tokens strictly to session/action intent: A password-reset 6-digit OTP must not be valid for phone verification or high-value payout confirmation! Include
purpose("password_reset"vs"2fa_login") alongsideuser_idinside server-side OTP records, and invalidate immediately on first valid consumption (single-use).
Bottom line: Mint secrets strictly with cryptographic RNGs, store hashed high-entropy API tokens instead of plaintext, enforce strict attempt caps and short TTLs on 6-digit OTPs, treat User-Agent strictly as diagnostic telemetry, and validate redirect URLs aggressively at auth boundaries.
Try a free tool
Every tool runs in your browser with no account required.