REST API Security Best Practices
# CHAPTER 24
REST API Security Best Practices
1. Introduction
If you build a beautiful, fast API but leave the doors unlocked, hackers will exploit it in minutes. Security is not an afterthought; it must be baked into every layer of your API. In Chapter 24, we will cover the critical security best practices every API developer must know. We will discuss HTTPS, defend against SQL Injection and XSS, and demystify the dreaded CORS (Cross-Origin Resource Sharing) errors.2. Learning Objectives
By the end of this chapter, you will be able to:- Explain why HTTPS/TLS is non-negotiable for REST APIs.
- Prevent SQL Injection using PDO.
- Understand and configure CORS headers correctly.
- Prevent Cross-Site Scripting (XSS) by encoding output.
- Hide sensitive server information in HTTP headers.
3. Beginner-Friendly Explanation
Imagine your API is a fortress.- HTTPS: The armored truck that securely transports data to and from the fortress. Without it, anyone on the street can read your mail.
- SQL Injection Prevention: Checking everyone's pockets at the gate to ensure they aren't carrying a bomb designed to blow up your database.
- CORS: The guest list. Telling the browser exactly which other websites are allowed to talk to your fortress via JavaScript.
- XSS Prevention: Ensuring that if a user writes graffiti on the fortress walls, it is treated as harmless paint, not as instructions for the guards to follow.
4. Real-World Examples
-
CORS Error: You build a React app on
http://localhost:3000and try to fetch data from your PHP API onhttp://localhost:8000. The browser blocks it with a red error in the console. This is CORS protecting the user!
- Data Breach: A company fails to use HTTPS. A user logs in at a public coffee shop. A hacker on the same Wi-Fi intercepts the HTTP packet in plain text and steals the API token.
5. Detailed Code Examples
Let's look at how to properly configure CORS in PHP and how to hide PHP version information.1. Secure Headers (index.php):
2. Hiding PHP Version (php.ini):
By default, PHP sends a header like X-Powered-By: PHP/8.1.2. Hackers use this to find known vulnerabilities in that specific PHP version.
Turn it off in your php.ini file:
6. Request/Response Examples
A securely configured API response will include several security headers.Response:
7. HTTP Examples
HTTPS vs HTTP: Never accepthttp:// requests for an API. At the server level (Apache/Nginx), configure a redirect so that any traffic hitting port 80 (HTTP) is instantly redirected to port 443 (HTTPS). Without HTTPS, API keys and JWTs are sent in plain text across the internet.
8. JSON Examples
To prevent XSS (Cross-Site Scripting), ensure that if a user submits malicious HTML in a JSON payload, you encode it before returning it to the frontend.Input Payload:
Output Payload (Sanitized via htmlspecialchars in PHP):
*Now, when the frontend displays the comment, it shows as raw text instead of executing the dangerous script.*
9. Best Practices
- Never trust user input: Always use PDO Prepared Statements. We covered this in Chapter 21, but it is the single most important security rule in backend development.
-
Principle of Least Privilege: Ensure the MySQL user your API connects with only has permissions to
SELECT,INSERT,UPDATE,DELETE. It should not haveDROP TABLEorGRANTpermissions.
- Rate Limiting: Protect your endpoints from Brute Force and DDoS attacks by limiting how many requests a single IP can make per minute. (We cover this in the next chapter).
10. Common Mistakes
-
Access-Control-Allow-Origin: *in Production: While*is fine for public, read-only APIs (like a weather API), it is highly dangerous for authenticated APIs. If you use*, ANY website on the internet can make JavaScript requests to your API. Always lock it down to your specific frontend URL.
-
Storing Passwords in Plain Text: Never store raw passwords. Always use PHP's
passwordhash()andpasswordverify()functions.
11. Mini Exercises
-
1.
Open a website, press F12, go to the Network tab, and click a request. Look at the Response Headers. Can you find the
Access-Control-Allow-OriginorX-Powered-Byheaders?
12. Coding Challenges
Challenge 1: Write a PHP snippet that takes an array$data = ["name" => "<script>bad</script>"], sanitizes the name value using htmlspecialchars(), and then jsonencodes it.
13. MCQs with Answers
What is the primary purpose of HTTPS?
Which HTTP header is used to resolve CORS errors in the browser?
How do you prevent SQL Injection in a PHP API?
14. Interview Questions
- Q: Explain what CORS is, why browsers enforce it, and how to configure an API to bypass it safely.
-
Q: Why is it dangerous to leave
exposephp = Onin your server configuration?
- Q: If an API requires a Bearer token, why is using HTTPS absolutely mandatory?