Skip to main content
API Security Tutorial
CHAPTER 04 Intermediate

Authentication Fundamentals

Updated: May 13, 2026
20 min read

# CHAPTER 4

Authentication Fundamentals

1. Introduction

With our HTTPS tunnel secured, we know no one is eavesdropping. However, we still don't know *who* is sending the requests. Before an API can serve private data, it must verify the identity of the client. In this chapter, we will define Authentication, clearly distinguish it from Authorization, and explore the evolution of API identity verification—from legacy session cookies to modern, stateless token architectures.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Clearly define the difference between Authentication (AuthN) and Authorization (AuthZ).
  • Understand how traditional Session-Based Authentication works.
  • Understand the paradigm shift to Stateless Token-Based Authentication.
  • Recognize the benefits of tokens (like JWTs) in modern REST APIs.
  • Identify common authentication attack vectors.

3. Beginner-Friendly Explanation

Authentication (AuthN) answers the question: *"Who are you?"* Authorization (AuthZ) answers the question: *"What are you allowed to do?"*

Imagine going to an airport.

  • Authentication: You show your Passport to the TSA agent. They verify your face matches the photo. They now know exactly *who* you are.
  • Authorization: You walk up to the First Class lounge. The lounge attendant looks at your boarding pass. Because you bought an Economy ticket, you are denied entry. You are authenticated (they know who you are), but you are *not authorized* to enter the lounge.

APIs work exactly the same way. The /api/login endpoint handles Authentication. Every subsequent API request handles Authorization.

4. Real-World Attack Scenarios

  • Credential Stuffing: Hackers buy millions of leaked username/password combos from a dark web breach (like a Yahoo hack) and use automated bots to test them against your API's /login endpoint. Because people reuse passwords, thousands of logins succeed.
  • Session Hijacking: An attacker steals a user's unencrypted session cookie. They paste that cookie into their own browser or Postman request. The API thinks the attacker is the legitimate user.

5. Evolution: Stateful vs Stateless Auth

1. Session-Based Auth (Stateful - The Old Way) When you log in, the PHP server creates a file in its memory (a Session). It sends a "Session ID" cookie back to your browser. Every time you make a request, the browser sends the cookie. The server looks up the cookie in its memory to find out who you are. *Problem:* If your API scales to 10 servers, Server A doesn't know about the session saved on Server B.

2. Token-Based Auth (Stateless - The Modern API Way) When you log in, the server mathematically generates a signed Token (e.g., a JWT) and gives it to you. The server does *not* save anything in its memory. When you send a request, you attach the Token. The server uses cryptography to verify the signature on the Token. Because the server doesn't rely on memory, it scales infinitely.

6. Vulnerable vs Secure Code Examples

Vulnerable (Brute Force Allowed):
php
12345678910
<?php
// A hacker can hit this endpoint 10,000 times a second trying to guess passwords
$email = $_POST[&#039;email'];
$password = $_POST[&#039;password'];

$user = $db->query("SELECT * FROM users WHERE email = &#039;$email'");
if (password_verify($password, $user[&#039;password'])) {
    echo "Logged in!";
}
?>

Secure (Rate Limited & Time Safe):

php
1234567891011121314151617181920212223
<?php
// Implement Rate Limiting (e.g., max 5 attempts per minute)
if (check_rate_limit($_SERVER[&#039;REMOTE_ADDR']) > 5) {
    http_response_code(429);
    die("Too many login attempts. Try again later.");
}

$email = filter_var($_POST[&#039;email'], FILTER_SANITIZE_EMAIL);
$password = $_POST[&#039;password'];

// Use prepared statements
$stmt = $db->prepare("SELECT password_hash FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();

if ($user && password_verify($password, $user[&#039;password_hash'])) {
    echo json_encode(["token" => generate_secure_token()]);
} else {
    // Return generic error. Never reveal if the email exists or not!
    http_response_code(401);
    echo json_encode(["error" => "Invalid credentials."]);
}
?>

7. HTTP Examples (Token Auth)

In a modern API, once the user logs in and receives a token, they must attach it to every subsequent request using the Authorization header.
http
123
GET /api/v1/bank-accounts HTTP/1.1
Host: api.bank.com
Authorization: Bearer abcdef1234567890secrettoken

8. JSON Examples

When designing a /login response, never send passwords back, and provide token expiration details.
json
123456789
{
  "status": "success",
  "data": {
    "user_id": 105,
    "access_token": "eyJhbGciOiJIUzI...",
    "token_type": "Bearer",
    "expires_in": 3600
  }
}

9. Best Practices

  • Use bcrypt/Argon2: Never store passwords in plain text or use MD5/SHA1. Always use PHP's built-in passwordhash() and passwordverify() functions.
  • Generic Error Messages: If a login fails, say "Invalid email or password." Do NOT say "User not found" or "Incorrect password." If you do, hackers can use your API to harvest a list of valid emails.
  • Stateless REST: REST APIs should ideally be stateless. Transition away from PHP $SESSION arrays and move toward JSON Web Tokens (JWTs).

10. Common Mistakes

  • Logging Passwords: Accidentally writing $password to a server text log file during debugging and forgetting to remove it in production.
  • Insecure Token Storage: Frontend developers storing tokens in localStorage making them vulnerable to XSS attacks, rather than storing them in HttpOnly secure cookies or secure mobile vaults.

11. Mini Exercises

  1. 1. Define the difference between Authentication and Authorization in one sentence each.
  1. 2. Why is storing passwords in MD5 considered a critical security vulnerability today?

12. Practice Challenges

Challenge: Look up the PHP documentation for the password
hash() function. Write a 3-line PHP script that takes a string "MySecurePass123", hashes it using the default algorithm, and prints it to the screen. Notice how long and complex the resulting string is.

13. MCQs with Answers

Question 1

Which term describes the process of verifying a user's identity ("Who are you?")?

Question 2

Why are traditional Session-based authentication systems difficult to use in modern, large-scale REST APIs?

Question 3

If a user logs in with an incorrect password, what is the most secure error message to return?

14. Interview Questions

  • Q: Explain the difference between Authentication and Authorization using a real-world analogy.
  • Q: What is the difference between Stateful and Stateless authentication? Why do REST APIs prefer Stateless?
  • Q: Explain "Credential Stuffing" and how you would protect your API's login endpoint against it.

15. FAQs

Q: Is it safe to build my own cryptography or token generation algorithm? A: Absolutely not. The number one rule of cybersecurity is "Never roll your own crypto." Always use industry-standard libraries, built-in PHP functions (password_hash), and established protocols (JWT/OAuth).

16. Summary

In this chapter, we clarified the fundamental difference between Authentication (identity) and Authorization (permissions). We explored the evolution from stateful, memory-heavy session cookies to modern, scalable, stateless token architecture. We also reviewed critical login security practices, emphasizing generic error messages, rate limiting, and utilizing strong password hashing algorithms like bcrypt.

17. Next Chapter Recommendation

Tokens are great for users, but what about computer-to-computer communication? Proceed to Chapter 5: API Keys and Secure Access to learn how to secure APIs designed for third-party developers and automated scripts.

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