API Keys and Secure Access
# CHAPTER 5
API Keys and Secure Access
1. Introduction
While User Authentication (Chapter 4) relies on emails and passwords, System-to-System communication requires a different approach. When a weather app on your server talks to a global meteorological API, there is no human typing in a password. Instead, we use API Keys. In this chapter, we will learn how API Keys function, how to generate and store them securely, the catastrophic risks of exposed keys, and how to implement key rotation.2. Learning Objectives
By the end of this chapter, you will be able to:- Understand the primary use cases for API Keys versus User Tokens.
- Design a secure database architecture to store and validate API Keys.
- Implement API Key validation via HTTP Headers in PHP.
- Understand the critical danger of committing API keys to Git repositories.
- Explain the concept and necessity of API Key Rotation.
3. Beginner-Friendly Explanation
Imagine a VIP parking garage.- User Authentication is like a human security guard. You roll down your window, show your driver's license, and they verify your face.
- An API Key is like an electronic toll pass (EZ-Pass) stuck to your windshield. The garage gate scans it wirelessly and opens instantly. It’s designed for fast, automated, machine-to-machine verification.
If someone steals the physical EZ-Pass from your car, they can enter the garage and the system will charge *your* account. Therefore, keeping that EZ-Pass (the API Key) a tightly guarded secret is the most important part of system-to-system security.
4. Real-World Attack Scenarios
-
The GitHub Scraping Disaster: A junior developer accidentally uploads their code to a public GitHub repository. They forgot to remove their
AWSAPIKEYfrom the code. Within 5 minutes, an automated bot scrapes GitHub, finds the key, and uses it to spin up hundreds of servers to mine cryptocurrency. The developer's company is billed $50,000 overnight.
- The Mobile App Extraction: A developer hardcodes a Google Maps API Key directly into their Android App's source code. A hacker reverse-engineers the app, extracts the key, and uses it for their own commercial application, exhausting the original developer's quota.
5. Security Examples (Generating a Key)
An API key must be long, random, and unguessable. Never use sequential IDs or basic words. In PHP, use cryptographically secure pseudo-random number generators (CSPRNG):6. Vulnerable vs Secure Code Examples (Validating Keys)
Vulnerable API (Key in URL, vulnerable to timing attacks):
Secure API (Key in Header, Time-safe comparison):
7. HTTP Examples
The industry standard is to pass API keys in a custom HTTP Header, keeping them out of URLs and browser histories.8. Database Architecture
How do you store API Keys in your MySQL database? Rule: Treat API Keys exactly like passwords. NEVER store them in plain text.- When the user generates a key, show it to them *once*.
-
Hash the key using
passwordhash()and store the hash in the database.
- If the user loses the key, they must generate a new one. You cannot recover it for them.
9. Key Rotation
If an employee leaves the company, or you suspect a key is compromised, you must "Rotate" the key.- 1. Generate a "New Key".
- 2. Keep the "Old Key" active for a grace period (e.g., 7 days) so the client's automated systems don't crash immediately.
- 3. The client updates their code to use the New Key.
- 4. After 7 days, delete the Old Key hash from the database.
10. Best Practices
-
Use
.envfiles: Never write an API key directly into your PHP or JavaScript files. Store them in a.envfile and ensure.envis added to your.gitignorefile so it is never uploaded to GitHub.
- Scope Your Keys: Give keys the minimum permissions necessary. If a key is only supposed to *read* weather data, it should not have permission to *delete* weather stations.
- Rate Limit by Key: Apply strict rate limits to individual API keys to prevent abuse or DDoS attacks (we will cover this in Chapter 13).
11. Common Mistakes
- Hardcoding Keys in Frontend Code: Putting an API key in a React, Angular, or Mobile app. Frontend code is public. Anyone can hit F12 and steal the key. If your frontend needs to call a 3rd party API, your frontend should call *your* PHP backend, and *your* backend (which securely holds the key) makes the call to the 3rd party.
12. Security Checklists
API Key Checklist:- [ ] Are keys passed via Headers (not Query Parameters)?
- [ ] Are keys hashed in the database?
- [ ] Are keys excluded from version control (.gitignore)?
- [ ] Does the system support key rotation?
- [ ] Are keys restricted by strict scopes/permissions?
13. Mini Exercises
- 1. What PHP function should you use to generate a secure, random string for an API key?
-
2.
Why should an API key never be sent in the URL (e.g.,
?key=123)?
14. Practice Challenges
Challenge: Review your codebase or a previous project. Did you ever hardcode a database password or a third-party API key directly into a.php file? Research how to set up a .env file in PHP to secure those credentials.
15. MCQs with Answers
What is the most secure way to transmit an API Key in an HTTP request?
How should API Keys be stored in your backend database?
What is the primary reason for NEVER hardcoding an API key into frontend JavaScript or Mobile App code?
16. Interview Questions
- Q: You notice a junior developer committed a Stripe API key to a public GitHub repository. What steps do you take to remediate this immediately?
- Q: Explain the concept of "Key Rotation" and why a grace period is necessary.
-
Q: Why must you use
passwordverifyorhash_equalsinstead of==when comparing an API key in PHP? *(Answer: To prevent Timing Attacks).*