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.
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?"
Valid JWT?
Right role?
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.
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.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.
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.
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.
email + password
saltRounds: 12
store hash, not password
email + password
SELECT from users
password vs hash
return token
Mounting the auth router
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.
(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.
Selective protection
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).
send refresh token
issue new access token
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.
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
Step 2 โ Log in and receive a token
Step 3 โ Access a protected route
Step 4 โ Try without a token
Step 5 โ Try an admin route as a regular user
- Store
JWT_SECRETin environment variables โ never commit it to git - Use
saltRounds: 12for bcrypt (10 is minimum, 14 is very secure but slow) - Set short access token expiry (
15mto1h) โ 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/loginwithexpress-rate-limitto prevent brute-force attacks
Quiz
bcrypt.compare() do?You completed the Authentication & Authorization quiz.
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 โ