1. Authentication vs Authorization

These two words are often confused, but they mean very different things and happen in sequence. You always authenticate first, then authorize.

๐Ÿชช

Authentication (AuthN)

Who are you? Proving your identity. A user submits an email and password. The server verifies it matches a known account. Result: the server knows who you are.

๐Ÿšฆ

Authorization (AuthZ)

What can you do? Enforcing permissions. Even after login, a regular user cannot delete products or access the admin dashboard โ€” only a user with role: "admin" can.

๐Ÿ›’
UrbanCart Example
Login vs admin dashboard

Amara logs in to UrbanCart โ€” that is authentication. She can view products, add to cart, and place orders โ€” that is authorization for a user role. She cannot access /admin/products to add new listings โ€” that requires role: "admin". The API checks both: first "are you logged in?" then "are you allowed?"

Request Flow
Request arrives
โ†’
AuthN
Valid JWT?
โ†’
AuthZ
Right role?
โ†’
Handler runs

2. Password Hashing with bcrypt

When a user registers, you must never store their password as plain text in the database. If the database is ever breached, every user's password is instantly exposed โ€” and because people reuse passwords, the damage extends far beyond UrbanCart.

Never do this: Storing password: "secret123" in plain text. Even MD5 or SHA-256 alone is not enough โ€” they're fast to reverse with rainbow tables. Use bcrypt.

bcrypt is a one-way hashing function designed for passwords. It is intentionally slow (you control the cost via saltRounds), and it embeds a random salt into every hash so two identical passwords produce different hashes.

saltRounds

The saltRounds value (also called the cost factor) controls how many times bcrypt runs its internal hashing loop. A value of 12 means 2^12 = 4096 iterations. Higher = slower to hash, but also slower for attackers to crack.

bcrypt-demo.js Hashing and comparing passwords
Output
Hash: $2b$12$KIXx7v1wW8zJr8Gf4p9m5uQV2sN8O3yT6pR1hD7cL0eM4bA9wZ3yi Match: true Wrong: false false
Key insight: bcrypt.compare() extracts the salt from the stored hash, rehashes the plain text password with it, then compares the result. You never need to store the salt separately โ€” it is baked into the hash string.

3. JWT โ€” JSON Web Tokens

After a user logs in successfully, the server needs to remember them for future requests. HTTP is stateless โ€” every request starts fresh. The classic solution is server-side sessions, but JWT (JSON Web Token) gives us a stateless alternative: the server signs a token and hands it to the client. The client sends it back on every request.

Structure: header.payload.signature

A JWT is three Base64URL-encoded strings joined by dots.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjQyLCJlbWFpbCI6ImRlbW9AdXJiYW5jYXJ0LmNvbSIsInJvbGUiOiJ1c2VyIiwiaWF0IjoxNzQ1MDAwMDAwLCJleHAiOjE3NDUwMDM2MDB9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Header โ€” algorithm & token type
Payload โ€” userId, email, role, expiry
Signature โ€” HMAC-SHA256 of header + payload + secret
๐Ÿ“ฆ

Payload (claims)

The payload is just JSON โ€” you put whatever you need to identify the user: userId, email, role. It is not encrypted, only Base64-encoded. Never put passwords or secrets in the payload.

โœ๏ธ

Signature

The server signs the header + payload using a secret key. If anyone tampers with the payload, the signature check fails. Only the server with the secret can issue valid tokens.

jwt-demo.js Sign and verify a JWT
Output
Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjQyLCJlbWFpbCI6ImRlbW9AdXJiYW5jYXJ0LmNvbSIsInJvbGUiOiJ1c2VyIiwiaWF0IjoxNzQ1MDAwMDAwLCJleHAiOjE3NDUwMDM2MDB9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c Decoded: { userId: 42, email: 'demo@urbancart.com', role: 'user', iat: 1745000000, exp: 1745003600 }
Where to store the JWT secret: Always in an environment variable (process.env.JWT_SECRET), never hard-coded in source code. Use a long random string โ€” at least 32 characters.

4. Login Flow โ€” Register & Login Endpoints

With bcrypt and JWT understood, we can build the two core auth endpoints for UrbanCart: POST /auth/register and POST /auth/login.

Registration Flow
POST /auth/register
email + password
โ†’
bcrypt.hash()
saltRounds: 12
โ†’
INSERT into users
store hash, not password
โ†’
Return userId
routes/auth.js POST /auth/register
Login Flow
POST /auth/login
email + password
โ†’
Find user by email
SELECT from users
โ†’
bcrypt.compare()
password vs hash
โ†’
jwt.sign()
return token
routes/auth.js POST /auth/login

Mounting the auth router

server.js Register the auth routes

5. Auth Middleware โ€” verifyToken

Once a user is logged in and has a JWT, every request to a protected route must include that token. The conventional way is to send it in the Authorization header as a Bearer token: Authorization: Bearer <token>.

We write a middleware function called verifyToken that intercepts each request, extracts the token, verifies it with jwt.verify(), and attaches the decoded user to req.user so route handlers can use it.

middleware/auth.js verifyToken middleware
Middleware pattern recap: An Express middleware function receives (req, res, next). Call next() to pass control to the next handler, or res.json() to terminate the request early (e.g., returning 401).

6. Protecting Routes

Apply verifyToken as a middleware argument to any route you want to protect. Public routes (like /auth/register and /auth/login) need no middleware. Private routes get it inserted before the handler.

routes/profile.js Protected route example

Selective protection

routes/products.js Public read, protected write

7. Refresh Tokens โ€” Concept

Access tokens are short-lived (typically 15 minutes to 1 hour) to limit damage if they are stolen. But you can't ask users to log in again every hour. The solution is a refresh token.

โšก

Access Token

Short-lived (15 min โ€“ 1 hr). Sent in every API request header. If stolen, it expires soon. Verified without hitting the database โ€” purely stateless.

๐Ÿ”„

Refresh Token

Long-lived (7โ€“30 days). Stored securely (httpOnly cookie). Used only to get a new access token via POST /auth/refresh. Stored in the database so it can be revoked (logout).

Refresh Token Flow
Access token expires
โ†’
POST /auth/refresh
send refresh token
โ†’
Validate & rotate
issue new access token
โ†’
Continue using API
Implementation note: Refresh tokens add complexity. For this lesson, know the concept. In production use a library like passport-jwt or an auth service (Auth0, Clerk, Supabase Auth) that handles token rotation for you.

8. Role-Based Access Control

After verifying the JWT, we know who the user is. The payload includes their role โ€” e.g., "user" or "admin". A second middleware layer checks that role before the handler runs.

middleware/auth.js requireRole middleware factory
routes/admin.js Admin-only routes
What happens with wrong role
// Regular user tries to access /admin/users // verifyToken passes โ€” valid token // requireRole('admin') fails โ€” role is "user" HTTP 403 Forbidden { "error": "Access denied. Required role: admin" }

9. Full curl Flow

Here is the complete end-to-end authentication flow for the UrbanCart API โ€” from registering a new account to accessing a protected route.

Step 1 โ€” Register a new user

terminal POST /auth/register
Response
{"message":"User registered","userId":42}

Step 2 โ€” Log in and receive a token

terminal POST /auth/login
Response โ€” save the token
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjQyLCJlbWFpbCI6ImRlbW9AdXJiYW5jYXJ0LmNvbSIsInJvbGUiOiJ1c2VyIiwiaWF0IjoxNzQ1MDAwMDAwLCJleHAiOjE3NDUwMDM2MDB9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c","user":{"id":42,"email":"demo@urbancart.com","role":"user"}}

Step 3 โ€” Access a protected route

terminal GET /api/profile with Bearer token
Response
{"id":42,"email":"demo@urbancart.com","name":"Demo User"}

Step 4 โ€” Try without a token

terminal GET /api/profile without token
Response โ€” 401 Unauthorized
{"error":"No token provided"}

Step 5 โ€” Try an admin route as a regular user

terminal GET /admin/users with user-role token
Response โ€” 403 Forbidden
{"error":"Access denied. Required role: admin"}
๐Ÿ”
UrbanCart Production Note
Security checklist before deployment
  • Store JWT_SECRET in environment variables โ€” never commit it to git
  • Use saltRounds: 12 for bcrypt (10 is minimum, 14 is very secure but slow)
  • Set short access token expiry (15m to 1h) โ€” add refresh tokens for production
  • Always use HTTPS in production โ€” tokens in plain HTTP are trivially stolen
  • Return "Invalid credentials" for both wrong email and wrong password โ€” never reveal which one failed
  • Consider rate-limiting /auth/login with express-rate-limit to prevent brute-force attacks

Quiz

Question 1 of 5
Why should passwords never be stored as plain text in a database?
Question 2 of 5
What are the three parts of a JWT, separated by dots?
Question 3 of 5
What does bcrypt.compare() do?
Question 4 of 5
Where should the JWT secret key be stored?
Question 5 of 5
What is the difference between authentication and authorization?
0
/ 5
Great job!

You completed the Authentication & Authorization quiz.

Next Lesson

Introduction to Next.js โ†’
You've completed Node.js & Express! Next up: Arc E โ€” Next.js.
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

You just secured UrbanCart with bcrypt and JWT.
Now build a career that's equally hard to break.

Join the Best AI Programs โ€” three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses โ†’