Exercises — Guards & Authorization
Covers: guards vs middleware, CanActivate + ExecutionContext (getHandler/getClass), simulated token AuthGuard, SetMetadata + Reflector (getAllAndOverride), @Public(), @Roles() + RolesGuard, @CurrentUser() via createParamDecorator, request['user'] pattern, 401 vs 403 semantics, guard execution order, APP_GUARD registration, the decision-flow tree, real-JWT swap preview.
Part A — Concept Checks (closed book)
- Guards vs middleware: what does a guard have access to that middleware fundamentally cannot have, and why (in terms of route resolution)?
- The three possible outcomes of
canActivate(true/false/ throw) — what does the client receive for each? - Why does the AuthGuard throw
UnauthorizedExceptioninstead of returningfalsewhen the token is missing? Explain 401 vs 403 in "who are you" / "are you allowed" terms. - What do
context.getHandler()andcontext.getClass()return, and which NestJS feature makes them essential? - Write the
@Public()decorator from memory (it's 2 lines + an import). What doesSetMetadataactually do? - What does
reflector.getAllAndOverride(KEY, [handler, class])do, and which level wins when both have the metadata? - Why MUST AuthGuard be registered before RolesGuard? What exact failure occurs otherwise?
- Why is
APP_GUARDeffectively mandatory for these guards (not just nicer), per the lesson? - A route has no
@Roles()decorator — what does RolesGuard do and why is that the right default? - What does
createParamDecorator's callback receive, and how does@CurrentUser('id')differ from@CurrentUser()? - If a guard rejects, which layers never execute? Does the exception filter still run?
- When moving from the simulated token to real JWT, which pieces change and which stay identical?
Part B — Guided Exercises
B1. The full guard stack
- Build
public.decorator.ts,roles.decorator.ts,current-user.decorator.tsfrom memory first, then compare with the lesson. - Build
AuthGuardwith the simulatedvalidateToken(accepts tokens startingvalid-;adminin the token grants['admin','user']). - Build
RolesGuard. - Register both via
APP_GUARDin the correct order. - Decorate
TasksController:GETroutes@Public();POST/PATCHrequire auth;DELETE :idrequires@Roles('admin'). - Add
GET /tasks/mine(auth required) using@CurrentUser()— for now return the user object.
Checkpoint — run all six lesson scenarios with curl and match the expected envelopes: | Request | Token | Expect | |---|---|---| | GET /tasks | none | 200 | | POST /tasks | none | 401 "No token provided" | | POST /tasks | valid-user-token | 201 | | DELETE /tasks/1 | valid-user-token | 403 "Requires one of [admin] roles" | | DELETE /tasks/1 | valid-admin-token | 200 | | POST /tasks | garbage-token | 401 "Invalid or expired token" |
B2. Ownership — putting @CurrentUser to work
- Add
ownerId: numberto the Task interface;createstamps it from the current user's id. GET /tasks/minereturns only the caller's tasks.PATCH /tasks/:id: only the owner or an admin may update; otherwiseForbiddenException('You do not own this task'). Decide where this check lives — guard or service? Write one paragraph defending your choice (the lesson's decision matrix helps).
B3. Metadata override experiment
- Put
@Public()on the entireNotesController(class level), then@Roles('admin')on a single route inside it. - Test what happens to that route with no token. Explain the result using
getAllAndOverridesemantics — and notice the trap:@Rolesdoesn't imply authentication; who was supposed to attachuser?
Part C — Independent Challenges
C1. @RequiredHeaders() guard
Build a decorator @RequiredHeaders('x-client-version') + HeadersGuard that 400s (throw BadRequestException) when listed headers are missing. Pure metadata + Reflector practice with no auth involved.
C2. API-key guard for machine clients
ApiKeyGuard: routes marked @ApiKeyAuth() accept x-api-key: <key> where valid keys live in a hardcoded map { key → clientName }. Attach request['client'] and create a @CurrentClient() param decorator. These routes must bypass the Bearer-token AuthGuard — design how the two guards coexist (hint: AuthGuard can check the same metadata and step aside).
C3. Self-or-admin rule
GET /users/:id/tasks — a user may fetch their own list; admins may fetch anyone's. Implement as a SelfOrAdminGuard reading the :id param from request.params and comparing to request['user']. What subtle type bug lurks in comparing params.id to user.id?
C4. Hierarchical roles
Change semantics: roles are ranked user < moderator < admin. @MinRole('moderator') passes for moderator AND admin. Implement MinRoleGuard with a rank map. Discuss in a comment: why might explicit role lists still beat hierarchies in real systems?
Part D — Debug Drills
D1
providers: [
{ provide: APP_GUARD, useClass: RolesGuard },
{ provide: APP_GUARD, useClass: AuthGuard },
]Symptom: every @Roles('admin') route returns 403 "No user context found" even with a perfect admin token. Why?
D2
// main.ts
app.useGlobalGuards(new AuthGuard());Symptom: crash or undefined reflector at request time. What dependency is missing and what's the prescribed fix?
D3
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getClass(),
context.getHandler(),
]);Order of the array flipped vs the lesson. A controller is class-level @Public() but one route was meant to be overridden back to protected via handler metadata. What behavior changes? (Research what getAllAndOverride's array order means — first non-undefined wins.)
D4
private extractToken(request: Request): string | null {
return request.headers.authorization ?? null;
}Symptom: validateToken always fails even for Authorization: Bearer valid-user-token. What string is actually being validated?
D5
export const Roles = (roles: string[]) => SetMetadata(ROLES_KEY, roles);
// usage
@Roles('admin')Compiler error — or worse, if typed loosely, runtime weirdness where requiredRoles.some(...) iterates characters. What's the signature bug?
D6
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
if (!request.user) return false;
...
}This RolesGuard returns false for a missing user. What status does the client get, and why does the lesson prefer throwing here? Which status is semantically right for "no user context"?
Part E — Prediction Drills
Setup: lesson-complete stack (both guards global, tasks controller decorated as in B1).
GET /taskswithAuthorization: Bearer garbage— 200 or 401? (Careful: it's@Public()— trace where the guard returns.)DELETE /tasks/1with no Authorization header — 401 or 403? Which guard fires?- A new route with
@Roles('admin')but the developer forgot the app has AuthGuard globally... AuthGuard is temporarily removed. What does RolesGuard do with a valid-admin-token request? @Public()route: does the LoggingInterceptor still run for it? Do pipes?POST /taskswith valid token but invalid body — which layer rejects and doesrequest['user']exist at that point?
Part F — Stretch Goals
- Swap the simulated
validateTokenfor real@nestjs/jwtjwtService.verify()— confirm none of the decorators/guards structure changes (this is Module 07's territory; a taste now cements the "architecture holds" point). - Read about
ThrottlerGuardfrom@nestjs/throttler— compare guard-level vs middleware-level rate limiting (Module 06 tension). - Type safety: define a
JwtUserinterface and make@CurrentUser()andrequest['user']fully typed (declaration merging on Express'sRequest).
Self-Assessment Checklist
- I can write SetMetadata decorator + Reflector-reading guard pairs from memory
- I can articulate 401 vs 403 and produce each deliberately
- I know why guard order matters and how APP_GUARD ordering works
- I've built a param decorator with createParamDecorator (with and without
data) - I can trace the full decision tree: @Public → token → validity → @Roles → role match
- I know exactly what changes (and what doesn't) when real JWT arrives
Answers & Hints
A1: ExecutionContext — the resolved handler and controller class, hence route metadata/decorators. Middleware runs before route resolution completes, so it can never know the target handler.
A2: true → proceeds; false → automatic ForbiddenException 403; throw → your exception propagates to the filter (e.g., 401).
A3: Missing/invalid credentials is an identity problem → 401 Unauthorized ("who are you?"). 403 means identity known but permission denied. Returning false would mislabel identity failures as 403.
A4: The route method reference and the controller class — the two places decorators attach metadata; Reflector reads them.
A5: export const IS_PUBLIC_KEY = 'isPublic'; export const Public = () => SetMetadata(IS_PUBLIC_KEY, true); — SetMetadata attaches a key/value onto the route's metadata for later Reflector reads.
A6: Reads the key from handler and class; returns the first defined value in array order — handler-level overrides class-level as passed in the lesson.
A7: AuthGuard attaches request['user']; RolesGuard reads user.roles. Wrong order → RolesGuard sees no user → ForbiddenException "No user context found" for every role-restricted route.
A8: Both guards inject Reflector; main.ts can't supply it to new AuthGuard(). APP_GUARD lets the DI container construct them.
A9: Returns true — no @Roles() means no role restriction. Restrictive-by-decorator, permissive-by-default for authorization (authentication is still enforced by AuthGuard).
A10: (data, ctx) — data is whatever was passed to the decorator; with 'id' it returns user.id, with nothing it returns the whole user.
A11: Skipped: remaining guards, interceptors, pipes, controller, service. The exception filter DOES run and formats the rejection.
A12: Changes: validateToken body (jwtService.verify) + JwtService injection. Unchanged: @Public, @Roles, @CurrentUser, RolesGuard, registration, controller code.
D1: APP_GUARD providers execute in registration order — RolesGuard runs first, before any user is attached.
D2: Reflector can't be manually provided in main.ts. Fix: register via APP_GUARD provider in AppModule.
D3: With [class, handler], class-level metadata wins over handler-level — overrides at the route level are silently ignored; a class-level @Public() can no longer be tightened per-route.
D4: The whole header "Bearer valid-user-token" — the Bearer prefix was never stripped, so startsWith('valid-') is false.
D5: Should be a rest parameter: (...roles: string[]). Called as @Roles('admin'), the non-rest version receives a string, and 'admin'.some doesn't exist / or metadata holds a string whose iteration yields characters.
D6: 403 (auto ForbiddenException) — acceptable status here actually, but throwing an explicit ForbiddenException('No user context found') gives a debuggable message; some argue 401 is more correct since the real issue is missing authentication. The lesson throws explicitly for clarity and consistent envelopes.
E1: 200 — isPublic check returns true before token extraction; the garbage token is never inspected.
E2: 401 from AuthGuard ("No token provided") — it runs first and short-circuits; RolesGuard never sees the request.
E3: RolesGuard finds requiredRoles=['admin'], request['user'] is undefined → ForbiddenException "No user context found" (defensive branch) — even for a "valid" token, because nobody validated/attached it.
E4: Yes and yes — @Public only skips the auth logic inside AuthGuard; interceptors and pipes run normally.
E5: ValidationPipe (400). Yes — guards ran before pipes, so request['user'] exists; the request died at stage ④.
