API keys are one of the most widely used authentication mechanisms for applications, cloud services and third-party integrations. They allow software to communicate with APIs without requiring users to repeatedly enter credentials. However, because API keys often provide direct access to valuable resources, they are also a common target for attackers.
Common API Key Security Risks
- Hardcoded API Keys: Developers sometimes place API keys directly inside source code. If the code is uploaded to GitHub or shared accidentally, anyone can retrieve the key. Example: API_KEY = "123456789abcdef"
- Public Repository Exposure: Attackers continuously scan GitHub, GitLab and Bitbucket repositories for leaked credentials. Common targets include AWS Keys, Google Cloud Keys, OpenAI Keys, Azure Keys.
- Client-Side Storage: Embedding API keys inside JavaScript files, Android APKs, iOS applications, Browser source code, allows attackers to extract them through reverse engineering.
- Lack of HTTPS: Sending API keys over HTTP exposes them to interception through packet sniffing or Man-in-the-Middle (MITM) attacks.
- Excessive Permissions: Many API keys have unnecessary privileges. Example A reporting service only needs read access but receives full administrator permissions. If compromised, attackers gain control.
- No Expiration: API keys that never expire remain valid indefinitely. Long-lived credentials significantly increase organizational risk.
- Shared API Keys: Using a single API key across multiple applications makes it impossible to determine which application performed a specific action.
API Key Attack Techniques
- GitHub Secret Scanning: Attackers search public repositories using automated scripts. Example AWS_SECRET_ACCESS_KEY, OPENAI_API_KEY, GOOGLE_API_KEY.
- Reverse Engineering Mobile Apps: Attackers decompile APK files using tools like JADX, APKTool, MobSF, Hardcoded API keys can often be recovered within minutes.
- Network Traffic Analysis: If encryption is missing, packet capture tools can reveal API keys. Common tools include Wireshark, tcpdump, Burp Suite.
- Browser Inspection: JavaScript applications sometimes expose API keys directly. Attackers inspect Developer Tools(Network Tab, Request Headers).
- Log File Exposure: Applications occasionally log sensitive headers. Example Authorization(Bearer abc123), x-api-key(xyz987). Anyone with log access can retrieve these credentials.
Secure API Key Storage Methods
| Storage Method | Security Level |
|---|---|
| Source Code | Very Poor |
| Configuration File | Poor |
| Environment Variables | Good |
| Secret Manager | Excellent |
| Hardware Security Module (HSM) | Highest |
Lab: Secure API Key Management Using Environment Variables
Requirements
Python 3.x, VS Code or any text editor, Internet connection, A free API key (OpenWeatherMap, NewsAPI or any public API).
Step 1: Get a Free API Key
For this lab, use OpenWeatherMap.
- Create a free account and Generate an API key.
- Copy the generated key.
Example: 9603eceb483439d4d3aaf5d01eae639aStep 2: Create a Project Folder
mkdir API-Key-Lab
cd API-Key-Lab
Step 3: Create a Python File
Create a file named: weather.py
Step 4: Hardcode the API Key (Insecure Method)
import requests
API_KEY = "9603eceb483439d4d3aaf5d01eae639a"
city = "Delhi"
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}"
response = requests.get(url)
print(response.json())
Run:
python weather.pyThe API works correctly. Problem Anyone who can read the source code can steal the API key.
Step 5: Store the API Key as an Environment Variable
Windows (Command Prompt)
set API_KEY=9603eceb483439d4d3aaf5d01eae639aLinux/macOS
export API_KEY=9603eceb483439d4d3aaf5d01eae639aStep 6: Modify the Code
Replace the hardcoded key with:
import os
import requests
API_KEY = os.getenv("API_KEY")
city = "Delhi"
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}"
response = requests.get(url)
print(response.json())
Run:
python weather.pyThe application behaves the same, but the secret is no longer stored in the source code.
Step 7: Verify the Environment Variable
Windows
echo %API_KEY%Linux/macOS
echo $API_KEYThe stored API key should be displayed.
Step 8: Remove the API Key
Windows
set API_KEY=Linux/macOS
unset API_KEYNow run the program again. You should receive an authentication error because the application cannot find the API key.
Expected Output
When the key is available:
{
"name": "Delhi",
"main": {
"temp": 305.6
}
}
When the key is missing:
{
"cod":401,
"message":"Invalid API key"
}
Best Practices for API Key Security
- Store Keys Outside Source Code: Use Environment variables, Secret management systems, Secure configuration services. Example API_KEY = os.getenv("API_KEY").
- Use Secret Managers: AWS Secrets Manager, Azure Key Vault, Google Secret Manager, HashiCorp Vault.These services provide encryption, access control, auditing, and automated rotation.
- Rotate API Keys Regularly: A recommended rotation cycle is every 60-90 days, or immediately after any suspected exposure.
- Apply Least Privilege: Grant only the permissions required for the application. Example Instead of Administrator Access, Use Read Products Only.
- Restrict API Keys: Many providers support restrictions such as IP address, Domain, HTTP Referrer, Mobile application package, Geographic region. Even if a key is stolen, these restrictions reduce misuse.
- Implement Rate Limiting: Example policy 100 requests/minute, requests exceeding the limit should receive HTTP 429 Too Many Requests
API Key Security Case Study
Braintrust API Key Exposure (2026)
In May 2026, AI platform Braintrust disclosed a security incident in which attackers gained unauthorized access to part of its cloud infrastructure that stored customer API keys. Although the company reported limited evidence of customer impact, it treated the incident as a potential credential compromise and instructed all customers to immediately rotate their API keys. Braintrust also secured the affected systems, rotated internal secrets and conducted a security review.
Lesson Learned: Store API keys securely, encrypt sensitive credentials, enforce least-privilege access, continuously monitor cloud environments and rotate API keys immediately after any suspected compromise.