Polski

Tutorial · API security · Authentication

API security in practice – OWASP API Security Top 10, BOLA, JWT, mass assignment, rate limiting and webhook signatures (NestJS, Express)

The pierogi shop's API serves a mobile app, an in-store kiosk and a courier company's webhooks. We go through the OWASP API Security Top 10 (2023 edition) with working code – object and function level authorization in NestJS, JWT verification with jose, protection against mass assignment, rate limits, signed webhooks with replay protection, safe consumption of third-party APIs and secrets that never reach the logs.

By · · 18 min read

The pierogi shop's API has three main clients today: a mobile app, an ordering kiosk in the restaurant and a courier company that sends webhooks about delivery status. An API has no UI that "hides" buttons – every endpoint is available to anyone who can send an HTTP request. That's why OWASP maintains a separate risk list for APIs. In this tutorial we go through it with code I ran locally – together with the server's real responses.

Prerequisites: NestJS or Express (NestJS tutorial, Express tutorial), JWT and OAuth basics (authentication tutorial), TypeScript.

2023
current edition – OWASP API Security Top 10
API1
BOLA – object level authorization – number 1
15 min
max access token age – in this tutorial
5 min
webhook signature window – an older request = a suspected replay
IDRisk (2023)In shortWhere in this tutorial
API1Broken Object Level Authorizationsomeone else's order after changing the IDNestJS – BOLA
API2Broken Authenticationweak token verification, no login limitsJWT with jose
API3Broken Object Property Level Authorizationmass assignment and too many fields in responsesDTOs, zod
API4Unrestricted Resource Consumptionno limits on requests, size, paginationrate limiting
API5Broken Function Level Authorizationa customer calls a staff endpointroles guard
API6Unrestricted Access to Sensitive Business Flowsbots buying up a limited offerbusiness limits
API7Server Side Request Forgerythe API fetches a URL supplied by the clientOWASP Top 10
API8Security MisconfigurationCORS, detailed errors, no TLSheaders, CORS
API9Improper Inventory Managementforgotten versions and "shadow" APIsOpenAPI, versions
API10Unsafe Consumption of APIsblind trust in a partner's responseswebhooks, validation
Diagram: A request's path through the pierogi API's layers of defence

API1 and API5: object and function authorization (NestJS)

BOLA is IDOR in the API world: GET /orders/{id} returns an order without checking whether it belongs to the caller. BFLA is the same for functions: a customer calls PATCH /orders/{id}/status, meant for kitchen staff, because the endpoint only checked that someone was logged in.

NestJS orders module: owner, roles, DTOs and limits

src/orders.module.ts
import {
  Body, CanActivate, Controller, ExecutionContext, ForbiddenException, Get, Injectable, Module,
  NotFoundException, Param, ParseUUIDPipe, Patch, Req, SetMetadata,
} from '@nestjs/common';
import { APP_GUARD, Reflector } from '@nestjs/core';
import { Throttle, ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { IsIn, IsOptional, IsString, MaxLength } from 'class-validator';

interface User { id: string; role: 'customer' | 'staff' | 'admin' }
interface Order { id: string; customerId: string; status: string; total: number; note?: string }
type AuthedRequest = { user: User }; // set by the JWT guard (verifyAccessToken)

export const Roles = (...roles: User['role'][]) => SetMetadata('roles', roles);

/** API5 BFLA: endpoints marked @Roles(...) are closed to everyone else. */
@Injectable()
class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}
  canActivate(ctx: ExecutionContext): boolean {
    const roles = this.reflector.getAllAndOverride<User['role'][]>('roles', [ctx.getHandler(), ctx.getClass()]);
    if (!roles) return true;
    const { user } = ctx.switchToHttp().getRequest<AuthedRequest>();
    if (!roles.includes(user.role)) throw new ForbiddenException();
    return true;
  }
}

class UpdateNoteDto {
  @IsOptional() @IsString() @MaxLength(300) note?: string;
}
class UpdateStatusDto {
  @IsIn(['preparing', 'ready', 'collected']) status!: string;
}

@Injectable()
class OrdersService {
  private readonly orders = new Map<string, Order>([
    ['0b9c6a1e-2f4d-4c55-9a7e-3c1f8d2b6a10', { id: '0b9c6a1e-2f4d-4c55-9a7e-3c1f8d2b6a10', customerId: 'cus_42', status: 'new', total: 64.5 }],
    ['7d41e2c3-8a9b-4f0e-b6d5-1a2b3c4d5e6f', { id: '7d41e2c3-8a9b-4f0e-b6d5-1a2b3c4d5e6f', customerId: 'cus_77', status: 'new', total: 38 }],
  ]);
  /** API1 BOLA: the owner is part of the lookup, not an afterthought. */
  findForCustomer(id: string, customerId: string) {
    const order = this.orders.get(id);
    return order?.customerId === customerId ? order : undefined;
  }
  findAny(id: string) { return this.orders.get(id); }
}

@Controller('orders')
class OrdersController {
  constructor(private readonly orders: OrdersService) {}

  @Get(':id')
  get(@Param('id', ParseUUIDPipe) id: string, @Req() req: AuthedRequest) {
    const order = this.orders.findForCustomer(id, req.user.id);
    if (!order) throw new NotFoundException();
    return order;
  }

  // API3: the DTO has only "note" – "status" or "total" in the body is rejected by the ValidationPipe.
  @Patch(':id/note')
  updateNote(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateNoteDto, @Req() req: AuthedRequest) {
    const order = this.orders.findForCustomer(id, req.user.id);
    if (!order) throw new NotFoundException();
    order.note = dto.note;
    return order;
  }

  // API5 + API4: staff only, with a tighter rate limit than the global one.
  @Patch(':id/status')
  @Roles('staff', 'admin')
  @Throttle({ default: { limit: 30, ttl: 60_000 } })
  updateStatus(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateStatusDto) {
    const order = this.orders.findAny(id);
    if (!order) throw new NotFoundException();
    order.status = dto.status;
    return order;
  }
}

@Module({
  imports: [ThrottlerModule.forRoot([{ ttl: 60_000, limit: 100 }])], // API4: a global budget per client
  controllers: [OrdersController],
  providers: [
    OrdersService,
    { provide: APP_GUARD, useClass: ThrottlerGuard },
    { provide: APP_GUARD, useClass: RolesGuard },
  ],
})
export class OrdersModule {}
src/main.ts
import 'reflect-metadata';
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import type { NextFunction, Request, Response } from 'express';
import { OrdersModule } from './orders.module.js';

const app = await NestFactory.create(OrdersModule, { logger: ['error'] });
// API3: strip unknown properties AND fail loudly when someone sends them.
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
// Demo only – in the real app a JWT guard sets req.user from a verified token.
app.use((req: Request & { user?: unknown }, _res: Response, next: NextFunction) => {
  const [id, role] = String(req.headers['x-demo-user'] ?? 'cus_42:customer').split(':');
  req.user = { id, role };
  next();
});
await app.listen(3009);
NestJS server responses (run locally, commands shortened)
$ curl -s localhost:3009/orders/7d41e2c3-8a9b-4f0e-b6d5-1a2b3c4d5e6f   # cus_42 asks for someone else's order
{"message":"Not Found","statusCode":404}
$ curl -s -X PATCH localhost:3009/orders/0b9c6a1e-…/note -H 'Content-Type: application/json' \
    -d '{"note":"bez cebulki","status":"collected","total":0}'
{"message":["property status should not exist","property total should not exist"],"error":"Bad Request","statusCode":400}
$ curl -s -X PATCH localhost:3009/orders/0b9c6a1e-…/status -d '{"status":"collected"}'   # as a customer
{"message":"Forbidden","statusCode":403}
$ curl -s -X PATCH localhost:3009/orders/0b9c6a1e-…/status -H 'x-demo-user: emp_3:staff' -d '{"status":"ready"}'
{"id":"0b9c6a1e-2f4d-4c55-9a7e-3c1f8d2b6a10","customerId":"cus_42","status":"ready","total":64.5}
  • The owner in the query (findForCustomer(id, req.user.id)) – not "fetch, then check", which is easy to forget in a new endpoint.
  • 404 for other people's objects – you don't reveal that the order exists.
  • Roles as metadata + a global guard (APP_GUARD) – a new admin endpoint without @Roles is a risk, so in bigger projects it's worth flipping the logic: deny by default and mark public endpoints explicitly (@Public()).
  • Tests with two accounts – the most effective BOLA test is an automated test where user B tries every endpoint with user A's identifiers.

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • API2: authentication and JWT pitfalls
  • API3: mass assignment and too much data in responses
  • API4 and API6: resource limits and sensitive flows
  • Webhooks: signature, time window, idempotency
  • API7, API8, API9, API10: SSRF, configuration, inventory, third-party APIs
  • Secrets and personal data out of the logs
  • Common mistakes
  • Test yourself
  • What's next

Create a free account · Sign in