Sikau

Project: An orders API · Day 4 · about 30 min

Guards: staff and kitchen

401 vs 403: who are you, and are you allowed to do this?

Not everyone can cook

Anyone may read the menu of orders, but only staff may create orders, and only the kitchen may move them along. A guard decides before the route runs: unknown caller → 401, known but not allowed → 403.

staff.guard.ts

import { CanActivate, ExecutionContext, ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common";

@Injectable()
export class StaffGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const req = context.switchToHttp().getRequest();
    if (req.headers["x-staff-key"] !== "momo-123") throw new UnauthorizedException("Staff only");
    if (req.url.includes("/advance") && req.headers["x-role"] !== "kitchen") throw new ForbiddenException("Kitchen only");
    return true;
  }
}

The rest of this lesson

  • Testing a guardexplain
  • Reading credentials in a guardexplain
  • Secrets don't belong in codeexplain
  • 401 or 403?predict
  • Identity or permission?match
  • Write the guardwrite code
  • Badge quizquiz
  • What you builtrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 5 lessons of Project: An orders API