Chapter 5: Authentication & Security
If you build a backend and fail at security, you will get fired. It is that simple. Protecting user data is the most critical responsibility of a backend engineer.
Rule #1: Never Store Plain Text Passwords
If a hacker steals your database, they will have a massive list of emails and passwords. Since users reuse passwords across the internet, the hacker can now log into their bank accounts.
You must hash passwords before saving them using a library like bcrypt. Hashing scrambles the password (e.g., password123 becomes $2b$10$abcdef...) in a way that is mathematically impossible to reverse.
// Example using bcrypt in Node.js
const bcrypt = require('bcrypt');
const saltRounds = 10;
const plainTextPassword = 'mySuperSecretPassword';
// Hash it before saving to the DB
const hashedPassword = await bcrypt.hash(plainTextPassword, saltRounds);
How Do Users Stay Logged In? (JWT)
HTTP is a "stateless" protocol. It has no memory. If you log in at /login, and then click a link to go to /profile, the server forgets who you are.
To solve this, we use JSON Web Tokens (JWT).
- User logs in with correct email/password.
- The server creates a long, scrambled string (the JWT) containing the user's ID, and signs it with a secret server key.
- The server sends the JWT to the frontend browser.
- The frontend saves it (usually in cookies or local storage).
- For every future request (like viewing the profile), the frontend attaches the JWT in the HTTP Header. The server verifies the signature and grants access.
OAuth 2.0 (Login with Google)
Instead of forcing users to create yet another password, modern apps use OAuth. This protocol allows your app to securely request the user's profile information from Google, GitHub, or Apple without ever seeing their actual password.
Mini Task: Inspect a JWT
- Go to jwt.io.
- This website explains exactly how the three parts of a token (Header, Payload, Signature) work.
- Paste a fake token into their debugger to see how it securely transmits data without being encrypted.