REST API Authentication Basics
# CHAPTER 13
REST API Authentication Basics
1. Introduction
Imagine building a banking API. If anyone could access the/accounts endpoint and withdraw money, it would be a disaster. APIs require a bouncer at the door to check IDs. This is called Authentication. Because REST is strictly stateless (no memory of previous interactions), authenticating REST APIs requires a very different approach than traditional website login pages. In Chapter 13, we will define authentication, explore why traditional sessions fail in REST, and introduce the concept of token-based authentication.
2. Learning Objectives
By the end of this chapter, you will be able to:- Define the term "Authentication" in the context of web APIs.
- Differentiate between Authentication (Who are you?) and Authorization (What can you do?).
-
Explain why traditional Server-Side Sessions (
$_SESSION) violate REST principles.
- Understand the basics of Token-Based Authentication.
- Describe how authentication data is transmitted via HTTP Headers.
3. Beginner-Friendly Explanation
- Authentication: Showing your ID card at the airport. It proves *who you are*.
- Authorization: Checking your boarding pass. It proves *where you are allowed to go*.
In a traditional website, when you log in, the server gives you an invisible wristband (a Session Cookie) and remembers you. As long as you stay on the website, you don't have to log in again. In a REST API, the server has amnesia. It forgets who you are the second it finishes serving you. Therefore, to get data, you must show your ID card (a Token) with *every single request you make*.
4. Real-World Examples
- Website Login: You log into Facebook on Chrome, close the tab, open it tomorrow, and you are still logged in (Stateful Session).
- API Login: A mobile weather app has a secret API Key stored in its code. Every time it asks the weather server for data, it attaches that key to the request to prove it's a legitimate app (Stateless Token).
5. Detailed Code Examples
Let's look at the architectural difference in code.The Old Way (Stateful - NOT RESTful):
The REST API Way (Stateless - Token Based):
6. Request/Response Examples
When making a protected API request, the client must include the authentication token in the Headers.Client Request without Token:
*Server Response: 401 Unauthorized*
Client Request WITH Token:
*Server Response: 200 OK*
7. HTTP Examples
The standard way to pass a token is using theAuthorization header.
Format: Authorization: <Type> <Credentials>
The most common type is Bearer, which literally means "give access to the bearer of this token."
8. JSON Examples
When a user logs into an API for the first time, the server generates a token and sends it back in the JSON payload. The client application must save this token (e.g., in LocalStorage on a browser, or Secure Storage on a mobile phone).9. Best Practices
- Always use HTTPS: If you send a token over plain HTTP, anyone watching the network (like someone on the same public Wi-Fi) can steal the token and impersonate the user. HTTPS encrypts the headers, making the token unreadable to spies.
-
Do not pass tokens in the URL: Never do
GET /data?token=abc123. URLs are logged in server access logs and browser histories. If the token is in the URL, it will be saved in plain text in multiple places. Always use theAuthorizationheader.
10. Common Mistakes
- Using Cookies for APIs: While cookies can be used securely, relying on them for APIs often leads to CORS (Cross-Origin Resource Sharing) issues and CSRF (Cross-Site Request Forgery) vulnerabilities. Header-based tokens are much safer for mobile apps and decoupled frontends (like React/Vue).
- Confusing AuthN and AuthZ: Authentication (AuthN) is identity. Authorization (AuthZ) is permissions. Don't mix up the logic.
11. Mini Exercises
- 1. Open an API testing tool (like Postman). Find the "Authorization" tab. Notice how it has different types like "Bearer Token", "Basic Auth", and "OAuth 2.0". These are all different methods of passing credentials.
12. Coding Challenges
Challenge 1: Write a PHP script that checks for anAuthorization header. If it is missing, return a 401 Unauthorized status code with a JSON error.
13. MCQs with Answers
Why are traditional PHP sessions ($_SESSION) bad for REST APIs?
Which HTTP Header is the standard place to put API tokens?
If a request lacks a valid authentication token, which status code should the API return?
14. Interview Questions
- Q: Explain the difference between Authentication and Authorization.
- Q: Describe how token-based authentication works in a stateless architecture.
- Q: Why is it a massive security risk to put API tokens in the URL query string?
15. FAQs
Q: How does the client get the token in the first place? A: Usually, the client sends a POST request to/login with an email and password. The server verifies those credentials against the database. If they match, the server generates a random string (the token), saves it in the database, and sends it back to the client.
Q: Can I use Basic Auth (username:password in the header)? A: Yes, but it is generally discouraged for modern APIs. Sending the actual password with every single request increases the risk of it being intercepted. Tokens are better because if a token is stolen, you can revoke (delete) the token without forcing the user to change their password.
16. Summary
In Chapter 13, we laid the theoretical foundation for API security. We learned that REST APIs must be stateless, meaning traditional server-side sessions cannot be used. Instead, we use Token-based authentication, where the client is responsible for proving their identity on every single request by including a secret token in theAuthorization header.