Skip to main content
RESTful Principles
CHAPTER 13 Beginner

REST API Authentication Basics

Updated: May 13, 2026
5 min read

# 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):

php
123456789
<?php
session_start();
// The server checks its own memory to see if this user is authenticated
if (isset($_SESSION[&#039;logged_in_user_id'])) {
    echo "Welcome back!";
} else {
    echo "Who are you?";
}
?>

The REST API Way (Stateless - Token Based):

php
12345678910111213
<?php
// The server relies entirely on what the client sends in the request
$headers = getallheaders();
$authHeader = $headers[&#039;Authorization'] ?? '';

// Check if the client provided the secret token
if ($authHeader === &#039;Bearer secret_token_123') {
    echo json_encode(["message" => "Authentication successful!"]);
} else {
    http_response_code(401);
    echo json_encode(["error" => "Unauthorized access. Please provide a valid token."]);
}
?>

6. Request/Response Examples

When making a protected API request, the client must include the authentication token in the Headers.

Client Request without Token:

http
12
GET /my-private-data HTTP/1.1
Host: api.example.com

*Server Response: 401 Unauthorized*

Client Request WITH Token:

http
123
GET /my-private-data HTTP/1.1
Host: api.example.com
Authorization: Bearer secret_token_123

*Server Response: 200 OK*

7. HTTP Examples

The standard way to pass a token is using the Authorization 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).
json
123456789
{
  "success": true,
  "message": "Login successful",
  "data": {
    "user_id": 45,
    "name": "Jane",
    "access_token": "abc123xyz987"
  }
}

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 the Authorization header.

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. 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 an Authorization header. If it is missing, return a 401 Unauthorized status code with a JSON error.

13. MCQs with Answers

Question 1

Why are traditional PHP sessions ($_SESSION) bad for REST APIs?

Question 2

Which HTTP Header is the standard place to put API tokens?

Question 3

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 the Authorization header.

17. Next Chapter Recommendation

Now that we understand the theory of tokens, let's implement them. Proceed to Chapter 14: API Keys and Token Authentication to see the database design and PHP logic required to build a custom token system.

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: ·