Authentication Fundamentals
# 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
/loginendpoint. 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):Secure (Rate Limited & Time Safe):
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 theAuthorization header.
8. JSON Examples
When designing a/login response, never send passwords back, and provide token expiration details.
9. Best Practices
-
Use bcrypt/Argon2: Never store passwords in plain text or use MD5/SHA1. Always use PHP's built-in
passwordhash()andpasswordverify()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
$SESSIONarrays and move toward JSON Web Tokens (JWTs).
10. Common Mistakes
-
Logging Passwords: Accidentally writing
$passwordto a server text log file during debugging and forgetting to remove it in production.
-
Insecure Token Storage: Frontend developers storing tokens in
localStoragemaking them vulnerable to XSS attacks, rather than storing them inHttpOnlysecure cookies or secure mobile vaults.
11. Mini Exercises
- 1. Define the difference between Authentication and Authorization in one sentence each.
- 2. Why is storing passwords in MD5 considered a critical security vulnerability today?
12. Practice Challenges
Challenge: Look up the PHP documentation for thepasswordhash() 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
Which term describes the process of verifying a user's identity ("Who are you?")?
Why are traditional Session-based authentication systems difficult to use in modern, large-scale REST APIs?
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).