CHAPTER 08
Beginner
Authentication and Authorization
Updated: May 14, 2026
25 min read
# CHAPTER 8
Authentication and Authorization
1. Introduction
If a hacker bypasses your Load Balancer and API Gateway, your last line of defense is knowing exactly who is requesting data and whether they have the legal right to access it. A massive percentage of system design catastrophic failures—data breaches, leaked passwords, and unauthorized financial transfers—occur because engineers confuse the concepts of Authentication and Authorization, or deploy insecure stateful session architectures that cannot scale. In this chapter, we will master Authentication and Authorization. We will securely store passwords, compare the massive scalability differences between traditional Sessions and modern JSON Web Tokens (JWT), and explore the decentralized power of OAuth.2. Learning Objectives
By the end of this chapter, you will be able to:- Define the critical difference between Authentication and Authorization.
- Explain why storing plain-text passwords is an architectural crime (Hashing vs. Encryption).
- Compare stateful Server Sessions against stateless JSON Web Tokens (JWT).
- Architect a highly scalable, stateless JWT authentication flow.
- Understand the basics of OAuth 2.0 and Single Sign-On (SSO).
3. Authentication vs. Authorization
These are not the same thing. Mixing them up leads to security breaches.- Authentication (Who are you?): The process of verifying a user's identity. (e.g., A user provides an email and a password. The system verifies they match).
- Authorization (What are you allowed to do?): The process of verifying a user's permissions. (e.g., The system knows you are John. But is John allowed to delete the database? No, because John has the role of 'Viewer', not 'Admin').
4. Storing Passwords (Hashing)
Never store plain text passwords in a database. If the database is hacked, the hacker has millions of passwords they can use to log into users' bank accounts.-
The Rule: You must use a Cryptographic Hash function (like
bcryptorArgon2).
-
How it works: A hash is a one-way mathematical function. It turns the password
apple123into$2b$12$L7.... It is mathematically impossible to reverse the hash back into the wordapple123.
- The Verification: When a user logs in, the server hashes the password they just typed and compares the *new hash* to the *saved hash* in the database.
5. Stateful Sessions (The Scaling Problem)
The traditional way to keep a user logged in.-
The Flow: User logs in. Server creates a "Session" in its local RAM (
Session ID: xyz123 = User: John). Server sends a cookie containingxyz123to the browser. Every subsequent HTTP request includes the cookie. The server looks upxyz123in its RAM, sees it's John, and approves the request.
- The Architecture Flaw: As discussed in Chapter 2, if you have 100 Web Servers, and Server 1 holds John's session in its RAM, John's next request *must* be routed to Server 1. If it hits Server 2, Server 2 has no idea who John is, and logs him out. This breaks Horizontal Scaling.
- The Patch: To fix this, architects must move the Sessions out of local RAM and into a centralized, distributed Redis Cache. Now, all 100 servers check Redis to verify the session.
6. JSON Web Tokens (Stateless Scaling)
JWTs solve the scaling problem by removing the server's memory entirely.-
The Flow: User logs in. Server verifies password. The Server creates a JWT (a long cryptographic string) that contains the user's data payload (
{"userId": 5, "role": "admin"}). Crucially, the server signs the token using a secret cryptographic key, and sends it to the client.
- The Magic: The server saves *nothing* in its RAM or Database. It forgets the user instantly.
-
The Verification: When the user makes their next API request, they attach the JWT. The server uses its secret key to verify the cryptographic signature of the JWT. If the signature is valid, the server trusts the data inside the token (
userId: 5).
- The Benefit: Because the token itself contains all the required proof, the server doesn't need to check a database or Redis cache. Infinite horizontal scaling with zero memory overhead.
7. Diagrams/Visual Suggestions
*Architecture Diagram: Stateless JWT Authentication*
text
8. Best Practices
-
Role-Based Access Control (RBAC): Build Authorization logic early. Every user should have a
role(e.g.,guest,user,admin). Every sensitive API endpoint must check the user's role before executing logic. If an API blindly trusts that only Admins will access the Admin Dashboard, a hacker will manually hit the/deleteUserendpoint and bypass the UI entirely.
9. Common Mistakes
- The Un-revokable JWT: Because JWTs are stateless and the server doesn't track them in a database, you cannot easily "log out" a user or ban them instantly. If a hacker steals a JWT, they can use it until it expires. *The Fix:* JWTs MUST have a very short expiration time (e.g., 15 minutes). To keep the user logged in seamlessly, architects implement a complex "Refresh Token" system to silently generate new short-lived JWTs in the background.
10. Mini Project: Trace an OAuth Login (SSO)
Why build your own login when Google can do it?- 1. The Goal: Add "Log in with Google" (OAuth 2.0).
- 2. The Redirect: User clicks the button. Your app redirects them to Google's highly secure servers.
- 3. The Auth: The user logs into Google (handling 2FA, passwords, etc.). Google asks: "Do you allow this app to see your email?"
- 4. The Callback: Google redirects the user back to your app with an "Authorization Code."
- 5. The Token: Your backend server securely trades that Code with Google's API for an "Access Token," proving the user's identity without your server *ever* seeing or storing their actual password.
11. Practice Exercises
- 1. Define the difference between Authentication and Authorization. Give a real-world example of an interaction failing due to an Authorization error.
- 2. Explain why storing "Stateful Sessions" in the local RAM of a web server destroys the ability to perform simple Horizontal Scaling.
12. MCQs with Answers
Question 1
When engineering a massive, horizontally scaled distributed system, why is the JSON Web Token (JWT) architecture heavily preferred over traditional Server-Side Sessions?
Question 2
A junior developer writes backend code that saves user passwords as plain text in the PostgreSQL database. Why is this considered an extreme security violation, and what cryptographic process MUST be used instead?
13. Interview Questions
- Q: Explain the mechanical difference between Hashing a password and Encrypting a password. Why do we strictly Hash passwords, but Encrypt credit card numbers?
- Q: Walk me through the security vulnerability of "Stateless" JWTs regarding compromised accounts. If a hacker steals a user's JWT, why is it incredibly difficult for the system architect to instantly revoke access, and how does the "Refresh Token" pattern mitigate this risk?
- Q: What is OAuth 2.0? Describe a scenario where an architect would choose to implement an external Identity Provider (like Auth0 or Okta) rather than building a custom username/password database from scratch.
14. FAQs
Q: Where should the client (browser) store the JWT? A: Never store sensitive access tokens inlocalStorage. They are highly vulnerable to Cross-Site Scripting (XSS) attacks (where a malicious JavaScript plugin steals the token). Always store secure tokens in an HTTPOnly cookie, which is completely inaccessible to browser JavaScript.