API Security Best Practices in 2025: Keys, Tokens, and Secrets
API keys in environment variables. Rotating secrets. Token expiry. Least privilege. The complete 2025 API security checklist for developers.
The API key leakage problem
GitHub's secret scanning service detected over 1 million exposed secrets in public repositories in 2024. AWS, Stripe, GitHub, Twilio API keys — all committed accidentally and discovered within minutes by automated scanners that monitor public repositories in real time. The average time from commit to first malicious use: under 5 minutes.
This isn't a theoretical risk. Teams have received bills for tens of thousands of dollars in AWS charges within hours of accidentally committing credentials. Stripe has processed fraudulent charges on exposed payment API keys. The consequences are immediate and expensive.
Secret storage: the right hierarchy
- Secrets manager (HashiCorp Vault, AWS Secrets Manager, Doppler): The correct place for production credentials. Provides rotation, access policies, audit logs, and versioning. Applications fetch secrets at runtime — credentials never touch the codebase or environment files.
- .env files (local development only): Never committed. Add to .gitignore on day one. Use .env.example with placeholder values for documentation.
- CI/CD environment variables: Acceptable for CI/CD secrets. Set as masked variables. Never print to logs.
- Hardcoded in code: Never, under any circumstances.
API key design best practices
When generating API keys for your own platform:
- Generate with maximum entropy — PassGeni's API generates 40-character keys by default (same pattern as the Team API key format)
- Store only the SHA-256 hash server-side — never the raw key
- Show the key exactly once (at generation) with clear instruction to copy it immediately
- Build key rotation into your UI from day one — retrofitting it is painful
- Set default expiry on all API keys — 90 or 180 days forces regular rotation
- Scope keys to minimum necessary permissions
Scanning and detection
Set up secret scanning before you have an incident:
- GitHub Advanced Security / GitLab Secret Detection: Scans pushes and existing history for known secret patterns
- TruffleHog: Open source, scans git history with entropy analysis
- detect-secrets (Yelp): Pre-commit hook that blocks commits containing high-entropy strings
- GitGuardian: Real-time monitoring with incident response integration
Also: rotate any secret that might have been exposed, even if you can't confirm it was. The cost of rotation is low; the cost of a compromised credential is not.