Skip to main content
API Security Tutorial
CHAPTER 05 Intermediate

API Keys and Secure Access

Updated: May 13, 2026
20 min read

# 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 AWSAPIKEY from 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):
php
12345
<?php
// Generates a secure, 64-character random hexadecimal API key
$api_key = bin2hex(random_bytes(32)); 
echo "Your new API Key is: " . $api_key;
?>

6. Vulnerable vs Secure Code Examples (Validating Keys)

Vulnerable API (Key in URL, vulnerable to timing attacks):

php
12345678910
<?php
// NEVER pass keys in the URL query string! They get logged in server access logs.
$client_key = $_GET[&#039;api_key'];
$valid_key = "secret_12345";

// '==' is vulnerable to Timing Attacks (hackers can guess the key letter by letter based on how long the comparison takes)
if ($client_key == $valid_key) {
    echo "Access Granted";
}
?>

Secure API (Key in Header, Time-safe comparison):

php
12345678910111213141516
<?php
// Always expect keys in the HTTP Headers
$headers = apache_request_headers();
$client_key = $headers[&#039;X-API-KEY'] ?? '';

// Fetch the hashed key from the database for this specific client...
$db_hash = fetch_key_hash_from_db();

// Use password_verify to check the hash securely and prevent timing attacks
if (password_verify($client_key, $db_hash)) {
    echo json_encode(["data" => "Secure data granted."]);
} else {
    http_response_code(401);
    echo json_encode(["error" => "Invalid API Key"]);
}
?>

7. HTTP Examples

The industry standard is to pass API keys in a custom HTTP Header, keeping them out of URLs and browser histories.
http
123
GET /api/v1/weather?city=London HTTP/1.1
Host: api.weather.com
X-API-KEY: a1b2c3d4e5f6g7h8i9j0

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. 1. Generate a "New Key".
  1. 2. Keep the "Old Key" active for a grace period (e.g., 7 days) so the client's automated systems don't crash immediately.
  1. 3. The client updates their code to use the New Key.
  1. 4. After 7 days, delete the Old Key hash from the database.

10. Best Practices

  • Use .env files: Never write an API key directly into your PHP or JavaScript files. Store them in a .env file and ensure .env is added to your .gitignore file 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. 1. What PHP function should you use to generate a secure, random string for an API key?
  1. 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

Question 1

What is the most secure way to transmit an API Key in an HTTP request?

Question 2

How should API Keys be stored in your backend database?

Question 3

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 passwordverify or hash_equals instead of == when comparing an API key in PHP? *(Answer: To prevent Timing Attacks).*

17. FAQs

Q: Can I restrict an API key so it only works from a specific IP address? A: Yes! This is a highly recommended best practice. If you issue an API key to a corporate partner, you can configure your backend to reject any requests using that key unless they originate from the partner's known IP address.

18. Summary

In this chapter, we learned how to securely authenticate machine-to-machine communication using API Keys. We emphasized the catastrophic financial risks of leaking keys to public repositories like GitHub. We covered practical security implementations, including generating keys with CSPRNG, storing them as hashes in the database, passing them via HTTP Headers, and utilizing time-safe string comparisons in PHP.

19. Next Chapter Recommendation

API Keys are great for machines, but modern web and mobile apps require a robust, stateless token system for human users. Proceed to Chapter 6: JWT Authentication Security to explore the industry standard for modern API authorization.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·