Skip to content
NestPath

Exercises — MongoDB + JWT Auth

Covers: - Part 1 (theory): stateless HTTP, session vs token auth, JWT anatomy (header/payload/signature), signed ≠ encrypted, access vs refresh tokens, rotation, reuse detection, frontend storage rules (memory vs HttpOnly cookie, never localStorage) - Part 2 (build): @nestjs/mongoose (@Schema, @Prop, SchemaFactory, @InjectModel), User/Task schemas, timestamps, unique indexes (E11000), bcrypt (12 rounds), AuthService (register/login/refresh/logout), minimal-payload refresh tokens, hashed refresh tokens in DB (multi-device array), AuthController with @Res({ passthrough: true }) + cookie options (httpOnly/secure/sameSite/path/maxAge), enumeration-safe "Invalid credentials", real-JWT AuthGuard, ConfigModule/.env, Mongo-backed TasksService with ownerId, full login→refresh→logout traces.

This module is split into 7A (Theory) and 7B (Build), mirroring the lesson.


Part A — Concept Checks (closed book)

7A — Token theory

  1. "HTTP is stateless" — explain why that fact alone creates the auth problem, and how sessions vs JWTs each solve it. What's the scaling pain with sessions?
  2. Name the three parts of a JWT and what each contains. Which parts can anyone read, and what does the signature actually prove?
  3. Why must you never put secrets in a JWT payload? Signed vs encrypted — one sentence each.
  4. State the security/UX trade-off that the two-token system resolves. Give the typical lifespans and storage locations for each token.
  5. What is refresh-token rotation and what attack does it mitigate? Describe reuse detection and the "nuke all sessions" response.
  6. Why store the access token in React memory instead of localStorage? Why does "it disappears on page refresh" not ruin UX?
  7. Why does the refresh token live in an HttpOnly cookie, and which two attack classes do httpOnly and sameSite: 'strict' each address?
  8. Why does the refresh token payload contain only { sub } while the access token carries { sub, email, roles }?
  9. Why is the refresh token absent from the login response body? How does it reach /auth/refresh at all?
  10. Why does login return "Invalid credentials" for both unknown email and wrong password?

7B — Implementation

  1. Map raw Mongoose to NestJS: schema definition, model injection, querying — the three-line translation table.
  2. What do @Schema({ timestamps: true }), @Prop({ unique: true }), and @Prop({ lowercase: true, trim: true }) each do? What MongoDB error code do unique violations raise?
  3. Why is refreshTokens an array of hashed strings on the User document? Two separate "why"s in there.
  4. Why bcrypt with 12 rounds for passwords, and why hash refresh tokens with the same care?
  5. What does @Res({ passthrough: true }) do, and what breaks (specifically, from Module 04) without passthrough?
  6. Explain each cookie option: httpOnly, secure (and its NODE_ENV condition), sameSite: 'strict', path: '/auth', maxAge.
  7. Which auth endpoints need @Public() and why is that obvious once said aloud?
  8. In the guard, what three things does jwtService.verify() check that your simulated startsWith('valid-') never did?
  9. Why Promise.all when signing the two tokens?
  10. Registration returns no tokens in the lesson. What's the design choice being made, and what's the alternative?

Part B — Guided Exercises

B1. Theory drills before touching code

  1. Go to jwt.io, paste any sample token, and identify header/payload/signature. Change one payload character and explain what the server-side verification would say.
  2. Draw the four boxes from memory: REGISTER, LOGIN, EXPIRED-TOKEN REFRESH, LOGOUT — with exactly what the client sends, what the server does, and what comes back (incl. cookies).
  3. Write the page-load initAuth() flow: what call, what does the browser attach automatically, what are the two branches?

B2. Mongo foundation

  1. Install: @nestjs/mongoose mongoose @nestjs/config @nestjs/jwt bcrypt cookie-parser (+ @types/bcrypt @types/cookie-parser).
  2. .env: MONGODB_URI, JWT_ACCESS_SECRET, JWT_REFRESH_SECRET, JWT_ACCESS_EXPIRY=15m, JWT_REFRESH_EXPIRY=7d. Wire ConfigModule.forRoot({ isGlobal: true }) and MongooseModule.forRootAsync reading the URI from config.
  3. Create the User schema exactly as the lesson: email/username (unique, trimmed, lowercased email), password, roles: ['user'] default, refreshTokens: [].
  4. UsersService with create, findByEmail, findById, plus refresh-token array helpers (addRefreshToken, removeRefreshToken, removeAllRefreshTokens).
  5. Duplicate-key handling: register the same email twice; catch Mongo error 11000 and convert it into a ConflictException('Email or username already exists'). Verify the client sees your standard 409 envelope.

B3. Auth service + controller

  1. Implement register (bcrypt 12 rounds, no tokens returned).
  2. Implement login: find by email → bcrypt.compare → same "Invalid credentials" for both failure paths → sign both tokens (Promise.all, separate secrets/expiries, minimal refresh payload) → hash refresh token → push to user's refreshTokens → return { accessToken } + set the cookie with all five options.
  3. Implement refresh: read cookie → verify with refresh secret → load user → find matching hashed token in the array (bcrypt.compare loop) → reuse detection: valid signature but not in DB ⇒ wipe all the user's refresh tokens + 403 → otherwise rotate (remove old, issue+store new pair) → new cookie + new accessToken.
  4. Implement logout: remove the presented refresh token from DB, clear the cookie.
  5. cookie-parser in main.ts — without it request.cookies is undefined.

Checkpoint (curl, in order — save outputs):

bash
# 1. register → 201, no tokens
# 2. register again → 409
# 3. login (-c cookies.txt) → accessToken in body, refreshToken ONLY in Set-Cookie
# 4. GET /tasks with Bearer accessToken → 200
# 5. POST /auth/refresh (-b cookies.txt) → NEW accessToken + NEW cookie
# 6. POST /auth/refresh with the OLD cookie again → 403 (rotation caught the replay)
# 7. login again, logout, then refresh → 401/403

Step 6 is the whole point of rotation — do not skip it.

B4. Swap the guard to real JWT

Replace validateToken with jwtService.verify(token, { secret: accessSecret }) in try/catch. Confirm: @Public(), @Roles(), @CurrentUser(), RolesGuard, controller code — zero changes. Test with a hand-expired token (set expiry to 10s, wait, call) → 401.

B5. Tasks on MongoDB

  1. Task schema: title, description, done default false, priority, ownerId (Types.ObjectId, ref: 'User'), timestamps.
  2. Rewrite TasksService async with taskModel.find/findById/findByIdAndUpdate/findByIdAndDelete; keep TaskNotFoundException; handle CastError for malformed ObjectIds → 400 (note: ParseIntPipe is gone — ids are strings now; what replaces the id sanity check?).
  3. Ownership: create stamps ownerId from @CurrentUser('sub'); update/delete allowed for owner or admin.
  4. Confirm data survives a server restart — the entire reason this module exists.

Part C — Independent Challenges

C1. Multi-device sessions

Login from two "devices" (two curl cookie jars). Verify both refresh tokens coexist in the user document. Logout device A; prove device B still refreshes fine. Then add POST /auth/logout-all (removes every token — "sign out everywhere").

C2. Change-password flow

PATCH /auth/password (authenticated): body { currentPassword, newPassword } (validated per Module 02 C1 rules). Verify current password, hash + save the new one, then revoke all refresh tokens (why is that mandatory? answer in a comment). Current access tokens keep working until expiry — explain why that's an inherent JWT limitation and one mitigation strategy.

C3. Profile endpoint with field hygiene

GET /auth/me returns the user document without password and refreshTokens. Solve it two ways: Mongoose projection (.select('-password -refreshTokens')) and schema toJSON transform. Which protects you globally against future leaks?

C4. Seed script + roles

A standalone script (or OnModuleInit provider) that creates an admin user from .env credentials if none exists. Then re-verify the Module 05 DELETE admin scenario against real Mongo-backed users.


Part D — Debug Drills

D1

login works, but POST /auth/refresh always 401s with "no token". console.log(request.cookies) prints undefined. Two classic culprits — name both (one is a missing app.use(...), one is a curl flag).

D2

ts
const payload = this.jwtService.verify(refreshToken); // no options

Refresh works... even when given an access token in the cookie. Why is this a serious vulnerability and what one option fixes it?

D3

ts
if (!user) throw new NotFoundException('No user with that email');
const ok = await bcrypt.compare(password, user.password);
if (!ok) throw new UnauthorizedException('Wrong password');

Both branches "work". What attack does this enable and what's the fix?

D4

ts
await this.userModel.updateOne(
  { _id: userId },
  { $push: { refreshTokens: refreshToken } },  // raw token
);

Storage "works", refresh "works". What's the breach-scenario problem, and what comparison change does hashing force in the refresh handler?

D5

ts
@Post('login')
async login(@Body() dto: LoginDto, @Res() response: Response) {
  const result = await this.authService.login(dto, response);
  return result;
}

Symptom: the request hangs, or the TransformInterceptor envelope disappears on this route. What's missing in @Res() and why does it matter?

D6

ts
@Prop({ required: true, unique: true })
email: string;

Two users with the same email register fine on your machine. unique looked like validation — what is it actually, and why might the index not exist yet? (Research autoIndex / index build timing.)

D7

Refresh rotation implemented, but users get randomly logged out: the frontend fires two API calls simultaneously with an expired access token, both trigger /auth/refresh... walk through why the second refresh trips reuse detection and nukes the session. (This is a famous real-world race; naming it is enough — solving it is Part F.)


Part E — Prediction Drills

  1. Login response headers vs body: where exactly does each token appear?
  2. GET /tasks with the refresh token in the Authorization header — status and why (think secrets).
  3. Access token tampered (change one payload char) — which guard line rejects it and with what status?
  4. POST /auth/refresh from a browser tab on evil.com (user logged into your app) — does the cookie get sent? Which option decides?
  5. A stolen refresh token is replayed after the victim's app already refreshed — full server-side sequence and final status.
  6. Mongo is down; GET /tasks with valid token — which of your layers produces the client's response, and what does the client see vs your logs?

Part F — Stretch Goals

  1. Solve D7's race: allow a short grace period for the previous refresh token, or queue refreshes client-side; implement one.
  2. Add token jti (unique id per refresh token) so DB lookups are exact-match instead of bcrypt-compare loops; discuss the trade-off.
  3. Mongoose pre('save') hook to hash passwords at the schema layer — then argue where hashing should live (service vs schema) and pick a side.
  4. Add indexes for ownerId on tasks and measure find({ ownerId }) with .explain().

Self-Assessment Checklist

  • I can explain JWT anatomy and signed-vs-encrypted to a junior dev
  • I can whiteboard the login → expired → refresh → retry flow including cookies
  • Rotation + reuse detection implemented and proven via the replay curl test
  • Passwords and refresh tokens are both hashed; login errors don't enumerate users
  • I know every cookie option's purpose and the passthrough gotcha
  • Tasks persist in Mongo with ownership enforced; all previous layers still work untouched

Answers & Hints

A1: Every request must independently prove identity. Sessions: server stores per-user state, cookie holds an ID → memory growth + multi-server sticky-session/shared-store pain. JWT: state lives in the signed token; any server verifies with the secret → horizontal scaling.

A2: Header (algorithm), payload (claims: sub, email, roles, iat, exp), signature (HMAC of header+payload with server secret). Header+payload are Base64 — readable by anyone. The signature proves the content wasn't tampered with, i.e., the server issued exactly this payload.

A3: Base64 is encoding, not encryption — payload is public. Signed = tamper-evident; encrypted = unreadable. JWTs (JWS) are the former.

A4: Short-lived = safe but bad UX; long-lived = the reverse. Access: 15m–1h, memory/HttpOnly cookie, sent on every API call. Refresh: 7–30d, HttpOnly Secure cookie, sent only to /auth/refresh, revocable via DB.

A5: Every refresh issues a new refresh token and deletes the old from DB. A replayed stolen (already-rotated) token has valid signature but no DB match → reuse detected → revoke all the user's tokens (attacker tripped the alarm).

A6: localStorage is readable by any XSS payload. Memory dies on refresh — by design: page load calls /auth/refresh and the cookie silently restores the session.

A7: httpOnly → JS can't read it → XSS-proof. sameSite: 'strict' → not sent on cross-site requests → CSRF protection.

A8: Access token data is consumed by controllers on every request; refresh token only mints new tokens — minimal payload = minimal exposure if leaked.

A9: Only in Set-Cookie. The browser attaches it automatically to /auth/* (path option). Frontend code never touches it.

A10: Distinct messages let attackers enumerate registered emails.

A11: new Schema({...}) → @Schema() class with @Prop()s; model('User', schema) → @InjectModel(User.name) userModel: Model<UserDocument>; Model.find() → this.userModel.find().

A12: Auto createdAt/updatedAt; unique MongoDB index (violation = E11000); Mongoose value transforms before save.

A13: Array → one token per device (multi-device sessions; logout one device removes one). Hashed → a DB breach yields unusable values, same rationale as passwords.

A14: bcrypt is deliberately slow + salted; 12 rounds is the current sweet spot. Refresh tokens are long-lived credentials — raw storage = full impersonation on breach.

A15: Lets you set cookies while keeping Nest's normal return-value handling. Without it, Nest assumes manual response mode → TransformInterceptor (and serialization) stop applying to that route.

A16: httpOnly: JS-inaccessible. secure: HTTPS-only (off in dev because localhost is http). sameSite strict: same-origin only. path /auth: cookie never rides along to /tasks — minimal exposure. maxAge 7d: browser-side expiry matching token expiry.

A17: register, login, refresh — you can't require a token to obtain a token.

A18: Signature validity (secret), expiry (exp), and structural integrity/claims decoding.

A19: Independent signing operations — parallelize for latency.

A20: Explicit-login design (email verification flows fit naturally). Alternative: auto-login on register (return tokens immediately) — pure product choice.

D1: (1) app.use(cookieParser()) missing → request.cookies undefined; (2) curl without -b cookies.txt never sends the cookie.

D2: Without { secret: REFRESH_SECRET }, verify uses the default (access) secret — access tokens become valid refresh tokens, collapsing the two-token security model. Different secrets per token type is the fix (and the reason they exist).

D3: User enumeration. Same UnauthorizedException('Invalid credentials') for both.

D4: Raw tokens in DB = breach grants instant impersonation. Hashing forces the refresh handler to bcrypt.compare the presented token against each stored hash rather than equality lookup.

D5: @Res({ passthrough: true }). Bare @Res() switches Nest to manual mode: you must call response.json() yourself (hence the hang) and interceptors disengage.

D6: unique creates an index — enforcement happens in MongoDB, not Mongoose validation. If the index hasn't been built (existing collection, autoIndex off, or race at startup), duplicates slip through. Ensure indexes exist (syncIndexes) and handle E11000 regardless.

D7: Call A refreshes → rotation deletes token T1, stores T2. Call B (still holding T1) refreshes → T1 has valid signature but is gone from DB → reuse detection → all sessions revoked → logout.

E1: Body: { accessToken } (inside your success envelope). Headers: Set-Cookie: refreshToken=...; HttpOnly; ....

E2: 401 — signed with the refresh secret; the guard verifies against the access secret → signature mismatch.

E3: jwtService.verify throws inside try/catch → UnauthorizedException → 401 envelope.

E4: Not sent — sameSite: 'strict' blocks cross-site cookie transmission.

E5: Cookie parsed → signature valid → user loaded → no hash match in refreshTokens → reuse detection → remove ALL tokens → 403 Forbidden.

E6: Mongoose query rejects → unhandled non-Http error → AllExceptionsFilter → client: generic 500 envelope; logs: full connection stack trace. (TimeoutInterceptor might convert it to 408 first if buffering exceeds 5s — worth observing which wins.)