🗒 Cheat Sheet← Lesson
BitWithBite
Full-Stack Worksheet

🔒 JWT Authentication

Chapter: Node.js & Express — Backend APIs · Level ★★★ · Time: 25 min
SCORE___ / 20
NameClassDate
After this worksheet you can
Hash passwords with bcryptSign and verify JWTsWrite protect middlewareKeep secrets out of code
📚 Quick Recap

🎯 What you'll practice: Password hashing, JWT signing/verifying, and protected route middleware.

🧠 Section A · Concept Check ● BEGINNER 4 × 1 = 4

1bcrypt.hash() is:
2A request with no token should get status:
3The JWT secret should be stored in:
4jwt.verify() throws if the token:

🧮 Section B · Problem Solving ● INTERMEDIATE 2 + 3×3 = 11

5The token is usually sent in the header.
6jwt.sign() takes a payload, a secret, and options like In.
7Write the register logic: hash a password before saving a user.
8Write the login logic: compare password and sign a token if valid.
9Why must password comparison use bcrypt.compare() instead of ===?

🚀 Section C · Challenge ● CHALLENGE 5

10Design the protect middleware from scratch and apply it to a GET /api/profile route that returns req.user.
💭 Reflection — the most useful thing I learned:
A ___/4   B ___/11   C ___/5   Total ___/20 Teacher's Signature Parent's Signature
✂ answer key — fold or cut before handing out

1-B   2-B   3-B   4-B  |  5 = Authorization   6 = expires   7 = const hashed=await bcrypt.hash(password,10); await User.create({email,password:hashed});   8 = const valid=await bcrypt.compare(password,user.password); if(!valid)return res.status(401).json({error:'Invalid'}); const token=jwt.sign({id:user._id},process.env.JWT_SECRET,{expiresIn:'7d'});   9 = Because the stored password is a one-way bcrypt hash, not the original text — bcrypt.compare() re-hashes the input with the same salt and checks equality; a plain === would never match a hash to raw text  |  10 = function protect(req,res,next){const token=req.headers.authorization?.split(' ')[1];if(!token)return res.status(401).json({error:'No token'});try{req.user=jwt.verify(token,process.env.JWT_SECRET);next();}catch{res.status(401).json({error:'Invalid'});}} then app.get('/api/profile',protect,(req,res)=>res.json(req.user));

📄 Need offline practice?Print this worksheet or open the one-page cheat sheet.
🗒 Cheat Sheet