Authentication & Authorization Fundamentals
9 min read
Authentication & Authorization Fundamentals 🔐
Imagine you are running a highly popular pizza shop (your Express server). You have hungry customers (HTTP requests) coming in constantly. The web operates on a protocol called HTTP, which is inherently amnesiac. Every time a customer walks up to the counter, it’s like you’ve never seen them before in your life—even if they just paid you five seconds ago.
If you, the chef, forget who paid for the extra cheese every time a new customer walks in, you are going to have a bad time. You need a reliable way to remember things—who people are and what they are allowed to do—while handling hundreds of orders at once.
Welcome to the world of Authentication and Authorization.
1. Concepts: Session-based Auth vs Stateless JWTs ⚖️
Before we write any code, we need to understand the two fundamental concepts that keep our applications secure.
The Problem
Since HTTP doesn't remember previous requests, a user who logs in successfully would immediately be "forgotten" on their very next click. We need a mechanism to keep them logged in.
The Solution: Authentication & Authorization
Let's define these two terms, as they are often mixed up:
- Authentication (AuthN): Who are you? (Checking a customer's ID card to prove they are Bob).
- Authorization (AuthZ): What are you allowed to do? (Bob is a customer, so he can eat in the dining area, but he is not authorized to enter the kitchen and bake pizzas).
To solve the amnesia problem, the industry relies heavily on two primary architectures:
Approach A: Session-Based Authentication (The Old Reliable)
In this approach, the server does the heavy lifting of remembering.
- Bob logs in.
- The server creates a "Session" in its database or memory (a giant ledger) and writes:
"Session #12345 belongs to Bob". - The server hands Bob a tiny ticket with
#12345printed on it (stored in Bob's browser as a Cookie). - Next time Bob wants pizza, he shows the ticket. The server looks up
#12345in its ledger, finds Bob, and serves him.
Pros: Extremely secure and easy to revoke (you just erase Bob from the ledger).
Cons: Hard to scale. If your pizza shop grows into a franchise with 10 different branches (servers), they all need to share that one massive ledger to know who Bob is.
Approach B: Stateless JWTs (The Modern Standard)
JWT stands for JSON Web Token. In this approach, the server doesn't remember anything. It is entirely stateless.
- Bob logs in.
- The server packages Bob's basic info into a digital ID badge (the JWT), cryptographically signs it with an unforgeable wax seal (a Secret Key), and hands it to Bob.
- Next time Bob wants pizza, he shows his sealed badge.
- The server doesn't need to look up a ledger. It just inspects the wax seal. If the seal is perfectly intact and matches the server's secret stamp, the server knows the badge is authentic and serves Bob.
Pros: Infinitely scalable. You can have 1,000 servers, and as long as they all share the same "wax seal" (Secret Key), they can verify Bob's badge without needing to talk to a central database.
Cons: Harder to revoke instantly. If Bob goes rogue, his badge is still technically valid until it naturally expires.
(In modern REST APIs and Single Page Applications, JWTs are the dominant industry standard, so that is exactly what we will build today!)
2. Hashing Passwords Securely (bcrypt) and User Registration 🕵️♂️
The Problem
Users need to create accounts with passwords. If you store these passwords as plain text in your database (e.g., password: "ilovepizza123"), you are committing a cardinal sin of web development. If a hacker breaches your database, they now have the email and password of every single user.
The Solution: Hashing and Salting
We never store passwords. We store Hashes.
- Hashing is a one-way mathematical meat grinder. You put a password in, and it spits out a completely scrambled string of gibberish. You cannot reverse the grinder to get the password back.
- Salting is the act of throwing a handful of random data (salt) into the grinder along with the password. This ensures that even if two users have the exact same password ("123456"), their final hashes will look entirely different.
The Tool: bcrypt
bcrypt is an industry-standard algorithm intentionally designed to be slow. By making the meat grinder take a fraction of a second to compute, it protects your app from "Brute Force" attacks where hackers try millions of passwords a second.
Setup:
Get the latest version from npm:
npm install bcryptIndustry Practice: User Registration
Here is how you handle a secure registration route in Express.
const express = require('express');
const bcrypt = require('bcrypt');
const app = express();
app.use(express.json()); // Middleware to parse JSON bodies
// Mock Database (In reality, this would be MongoDB or PostgreSQL)
const usersDB = [];
app.post('/api/register', async (req, res) => {
try {
const { email, password } = req.body;
// 1. Check if user already exists
const existingUser = usersDB.find(u => u.email === email);
if (existingUser) {
return res.status(400).json({ error: 'User already exists!' });
}
// 2. Hash the password
const saltRounds = 10; // Industry standard. Balances security and performance.
const hashedPassword = await bcrypt.hash(password, saltRounds);
// 3. Save to database
const newUser = {
id: Date.now().toString(),
email,
password: hashedPassword // NEVER store the plain password!
};
usersDB.push(newUser);
res.status(201).json({ message: 'User registered successfully!' });
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
}
});Under the hood: bcrypt.hash() automatically generates a unique salt, attaches it to the password, runs it through the Blowfish cipher 2^10 times, and outputs a string that looks like $2b$10$wI8....
3. Generating and Verifying JSON Web Tokens (JWT) 🎟️
The Problem
Now that Bob is registered, he needs to log in. Once he logs in, we need to hand him that "magically sealed digital badge" we talked about earlier so he doesn't have to send us his password on every single request.
The Solution: JSON Web Tokens
A JWT is a long string separated by two dots, looking like this: xxxxx.yyyyy.zzzzz
- Header (
xxxxx): Contains metadata (what kind of token it is). - Payload (
yyyyy): The actual data you want to carry (e.g., User ID, User Role). Do not put sensitive info like passwords here! Anyone can read the payload. - Signature (
zzzzz): The cryptographic seal. It takes the Header, Payload, and your Server's Secret Key, and hashes them together.
The Tool: jsonwebtoken
Setup:
npm install jsonwebtokenIndustry Practice: User Login
Let's build the login route. We need to check Bob's password, and if it matches, hand him a JWT.
const jwt = require('jsonwebtoken');
// A super secret key that ONLY your server knows.
// In production, this lives in a .env file! (e.g. process.env.JWT_SECRET)
const JWT_SECRET = 'super_secret_pizza_key_dont_tell_anyone';
app.post('/api/login', async (req, res) => {
try {
const { email, password } = req.body;
// 1. Find the user
const user = usersDB.find(u => u.email === email);
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// 2. Verify the password
// bcrypt.compare safely checks the plain text password against the hashed one
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// 3. Generate the JWT (The Badge)
const payload = {
id: user.id,
email: user.email,
role: 'customer'
};
// Sign the token with an expiration time (security best practice)
const token = jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
// 4. Send the token to the user
res.status(200).json({
message: 'Login successful',
token: token
});
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
}
});Bob now has his token. His front-end application (React, Vue, etc.) will save this token and attach it to future requests.
4. Creating Auth Middleware to Protect Private Routes 🛡️
The Problem
Bob wants to view his order history at /api/orders. This is a private route. If we don't protect it, anyone on the internet can see Bob's pizza habits. We need a system at the front door that stops requests, checks for a valid JWT, and either kicks the user out or lets them through.
The Solution: Express Middleware
Middleware is essentially a bouncer at the door. It intercepts the incoming request, does some checks, and if everything looks good, it calls next() to let the request proceed to the actual route handler.
Industry Standard:
Clients send the JWT in the HTTP headers, specifically the Authorization header, using the "Bearer" format:Authorization: Bearer eyJhbGciOiJIUzI1Ni...
Industry Practice: The Auth Middleware
// middleware/auth.js
const jwt = require('jsonwebtoken');
const JWT_SECRET = 'super_secret_pizza_key_dont_tell_anyone';
const verifyToken = (req, res, next) => {
// 1. Check if the Authorization header exists
const authHeader = req.headers['authorization'];
if (!authHeader) {
// 401 Unauthorized
return res.status(401).json({ error: 'Access denied. No token provided.' });
}
// 2. Extract the token (Split "Bearer <token>" and grab the second part)
const token = authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Access denied. Malformed token.' });
}
try {
// 3. Verify the seal!
// This will throw an error if the token is altered, fake, or expired.
const decodedPayload = jwt.verify(token, JWT_SECRET);
// 4. Attach the decoded user data to the Request object
// This allows the next route to know exactly who made the request!
req.user = decodedPayload;
// 5. Let the user pass through the door
next();
} catch (error) {
// 403 Forbidden
return res.status(403).json({ error: 'Invalid or expired token.' });
}
};
module.exports = verifyToken;Using the Middleware on a Private Route:
Now, whenever you want to protect a route, you just drop verifyToken in the middle!
// Applying the bouncer to the VIP lounge
app.get('/api/orders', verifyToken, (req, res) => {
// Because the middleware attached req.user, we know exactly who this is!
const userId = req.user.id;
const userEmail = req.user.email;
res.status(200).json({
message: `Welcome to the VIP Pizza Lounge, ${userEmail}!`,
orders: [
{ id: 1, item: 'Large Pepperoni' },
{ id: 2, item: 'Garlic Bread' }
]
});
});
app.listen(3000, () => {
console.log('🍕 Server is running on port 3000');
});And just like that, your API is secured! You have successfully implemented industry-standard registration, login, and protected routing.
📚 Extra Reading & References
Challenge
Your Task: Implement Core Authentication and Authorization Logic
You are tasked with completing two critical security functions for a web API using placeholder bcrypt and jsonwebtoken libraries.
1. Complete the loginUser function:
- This function receives a plaintext
password, astoredHashfrom the database, and auserId. - It must first verify if the provided
passwordmatches thestoredHashusingbcrypt.compare(). - If the verification is successful, it must generate a JSON Web Token (JWT).
- The JWT payload must be an object containing the
userIdand aroleset to'user'. - The token must be signed using the secret key
'your_jwt_secret_key'. - The token must be configured to expire in
'1h'(1 hour). - The function should return the generated token string on success, or
nullon failure (password mismatch).
2. Complete the authMiddleware function:
- This function acts as route-protection middleware, receiving a request object
req. - It must extract the JWT from the
Authorizationheader. The header format is"Bearer <token>". - It must handle cases where the
Authorizationheader is missing or malformed, returning an object{ status: 401, message: 'No token provided' }. - It must verify the extracted token using
jwt.verify()and the same secret key from the login function. - If the token is valid, it should attach the decoded payload to
req.userand return the string'next'to simulate passing control to the next handler. - If the token is invalid (e.g., wrong signature, expired), it should return an object
{ status: 403, message: 'Invalid token' }.
Expected result
Your final code should correctly implement the logic within the two provided function stubs.
loginUserfunction:- It must invoke
await bcrypt.compare(password, storedHash)to check the password. - Inside a conditional check for a successful comparison, it must call
jwt.sign(). - The call to
jwt.sign()must include three arguments in the correct order: the payload object ({ userId, role: 'user' }), the secret key (SECRET_KEY), and the options object ({ expiresIn: '1h' }). - It should return the result of
jwt.sign()on success andnullotherwise.
- It must invoke
authMiddlewarefunction:- It should check for
req.headers.authorizationand ensure it starts with'Bearer '. - It must correctly split the header string to isolate the token part.
- It must use a
try...catchblock to handle verification errors. - The
tryblock will calljwt.verify(token, SECRET_KEY), assign the decoded payload toreq.user, and return'next'. - The
catchblock will catch any errors fromjwt.verify(e.g., expiration, invalid signature) and return the specified forbidden error object{ status: 403, message: 'Invalid token' }.
- It should check for