Skip to Content
Cloud Engineering Academy
4. API Development & Integration

Request validation, models, versioning and CORS

Reject bad input in layers (API Gateway models and validators, ASP.NET Core 10 validation, mass-assignment defences), version APIs on API Gateway, and finally understand CORS preflight on REST APIs, HTTP APIs and ASP.NET Core.

intermediate⏱ 1 h 30 min🟢 FreeDVA-C03SAA-C03SCS-C03

Assumes: .NET 10 LTS · ASP.NET Core 10 (AddValidation, AddCors) · AWS CLI v2 · Amazon.CDK.Lib 2.x · Region us-east-1. Verified against official sources on 2026-11-17.

Learning objectives

By the end of this lesson you can:

  • Design validation in layers: API Gateway REST API request validators and models (JSON Schema draft 4), ASP.NET Core 10 validation (AddValidation() and explicit validators), and domain rules — and explain why HTTP APIs have no request validation.
  • Defend against mass assignment (OWASP API3:2023) with dedicated request types, additionalProperties: false and UnmappedMemberHandling.Disallow.
  • Apply payload limits consistently: API Gateway 10 MB, Lambda 6 MB synchronous, your own much smaller limits in Kestrel.
  • Version APIs on API Gateway with /v1 paths, stages, API mappings and routing rules.
  • Explain CORS precisely — same-origin policy, simple vs preflighted requests, every Access-Control-* header, the credentials-and-wildcard rule — and configure it on HTTP APIs, REST APIs (OPTIONS mock integration plus gateway responses) and in ASP.NET Core.

Prerequisites

Why this matters in banking

Three real-world failure patterns:

  1. A statement-request endpoint binds the JSON body straight into the entity class. A tester adds "customerId": "CUS-00067890" to the body and receives another customer's statement. That is mass assignment, part of OWASP API3:2023 Broken Object Property Level Authorization.
  2. A partner sends a 9 MB JSON array to an endpoint that expects a 200-byte object. API Gateway accepts it (under 10 MB), Lambda deserialises it, and memory spikes cost money and latency for everyone.
  3. The new web banking front end cannot call the API: every request fails with "blocked by CORS policy". A developer "fixes" it with Access-Control-Allow-Origin: * plus credentials, which browsers reject anyway, then with "reflect whatever Origin arrives", which turns a browser safety feature into a hole.

The idea in plain language

Validation means rejecting input that does not match the contract as early and as cheaply as possible — but never only at the edge, because the edge can be bypassed or misconfigured. Think of it as the bank's front desk (gateway: is the form filled in?), the back office (application: are the values valid?) and the ledger rules (domain: is this allowed for this customer today?).

CORS (Cross-Origin Resource Sharing) is a browser rule. By default, JavaScript loaded from https://app.harbourline.example may send requests to https://api.harbourline.example but may not read the responses, because they are different origins (an origin is scheme + host + port). CORS lets the API tell the browser, "scripts from this origin may read my responses, use these methods and send these headers". It protects users' browsers, not your server.

Analogy: The same-origin policy is a bank branch rule that staff from another branch cannot read your customer files. CORS is the signed letter from your branch manager saying "staff from the High Street branch may read files of this type". A courier who is not staff (curl, a partner's server, an attacker's script running outside a browser) never asks for the letter — it was never what kept them out. Your vault door (authentication and authorisation) does that.

What problem the AWS service solves

API Gateway REST APIs can validate requests before your integration runs, which saves Lambda invocations and keeps junk out of logs:

  • A request validator checks that required parameters (path, query, headers) are present and not blank (it does not check their type or format), and/or that the body matches a model.
  • A model is a JSON Schema draft 4 document attached to a method per content type. If no model matches the request's content type, body validation is skipped — use $default as the content type to always validate.
  • Failures return 400 with gateway response type BAD_REQUEST_PARAMETERS or BAD_REQUEST_BODY, which you can customise (for example into problem details).

HTTP APIs do not support request validation (and have no mock integrations or custom gateway responses); your code must do all of it. Their CORS support is built in: configure it once and API Gateway answers preflight requests itself.

Limits (checked 2026-11-17): maximum payload 10 MB for REST and HTTP APIs (REST APIs reply 413 via REQUEST_TOO_LARGE, and that gateway response cannot be customised); synchronous Lambda invocation payload 6 MB each way; REST API model size 400 KB per API; mapping templates 300 KB.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
APIM validate-content / validate-parameters policiesREST API request validators + modelsJSON Schema draft 4 only; parameter checks are presence-only
APIM cors policyHTTP API CORS configuration; REST API OPTIONS methods + response headersREST APIs need you to wire OPTIONS and error responses yourself (or CDK does it)
[ApiController] automatic 400 with ValidationProblemDetailsASP.NET Core 10 minimal APIs AddValidation()Source-generated; returns 400 problem details before the handler
services.AddCors() / [EnableCors]Same in ASP.NET Core: AddCors, UseCors, RequireCorsUnchanged; decide whether the gateway or the app owns CORS
APIM versions / revisions/v1 resources, stages, custom-domain API mappings, routing rulesStages are environments, not versions
Front Door / App Gateway WAF body inspectionAWS WAF on REST API stages (not HTTP APIs)See API security
Kestrel MaxRequestBodySizeSame — plus the gateway's 10 MB and Lambda's 6 MB ceilingsSet your own limit far below both

Architecture

Security-boundary view: everything left of your code is defence in depth, not the control. Gateway validation can be skipped by a mis-set content type, removed in a later deployment, or absent entirely (HTTP APIs, local runs, a future move to ECS). The application must validate every input as if nothing in front of it existed, and authorisation (which customer, which account) lives only in the application.

Step-by-step implementation

Layer 1 — the gateway model (REST APIs)

Write the model in JSON Schema draft 4. Two choices matter for security: additionalProperties: false rejects unexpected fields such as customerId, and a pattern instead of format for dates (do not rely on format being enforced by a draft-4 validator).

statement-request.schema.json
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "StatementRequestBody",
  "type": "object",
  "additionalProperties": false,
  "required": ["fromDate", "toDate", "format"],
  "properties": {
    "fromDate": { "type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" },
    "toDate":   { "type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" },
    "format":   { "type": "string", "enum": ["pdf", "csv"] }
  }
}

Attach it to POST /v1/accounts/{accountId}/statement-requests with a validator that checks body and parameters, and mark the Idempotency-Key header as required. The gateway cannot check cross-field rules (toDate on or after fromDate) or ownership; that is layer 2 and 3.

Layer 2 — strict binding in ASP.NET Core

Three settings stop most junk before your handler runs:

  • Body size: set Kestrel's MaxRequestBodySize to something realistic (16 KB for this endpoint). On Lambda, Kestrel is not in the path, so also keep the gateway model tight and validate lengths.
  • Unknown JSON members: System.Text.Json skips unknown properties by default. Set UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow so {"customerId": ...} fails binding with 400 instead of being silently ignored — or worse, bound by a future refactor.
  • Dedicated request records: bind to StatementRequestBody, never to the StatementRequest entity. The entity's CustomerId, Status and CreatedAt are set by the server.

Layer 3 — validation rules

ASP.NET Core 10 adds built-in minimal API validation: call builder.Services.AddValidation(), annotate request types with DataAnnotations ([Required], [Range], [AllowedValues]) and optionally implement IValidatableObject for cross-field rules. A source generator discovers types from endpoint signatures; invalid requests get a 400 problem-details response before the handler runs. Things to know:

  • It validates query, header and body parameters, and recurses into nested objects and collections.
  • It does not reject unknown JSON members — that is the UnmappedMemberHandling setting above.
  • In .NET 10, [ValidatableType] is marked experimental (warning ASP0029 outside web projects), and nullable value-type parameters are not validated (fixed in .NET 11).
  • Missing metadata fails silently: if AddValidation() is not called in the assembly that declares the types, nothing is validated. Test it.

Harbourline's module project uses explicit validators (Accounts/RequestValidation.cs) that return Results.ValidationProblem(...), because its status-code table distinguishes 400 (shape: missing or malformed fields) from 422 (business rule: date range), and explicit code makes that visible. Both approaches are fine; mixing them without a rule is not.

Layer 4 — domain rules and authorisation

Ownership of accountId (via IAccountStore.GetAccountAsync(customerId, accountId)), statement period limits (for example at most 12 months, not before the account opened) and rate limits are checked in the domain. These can never be pushed to the gateway.

Version on API Gateway without confusing stages and versions

ToolWhat it isUse it for
/v1 resource prefixPart of the resource tree in one APISimple APIs where v1 and v2 share a backend
Stage (dev, test, prod)Named snapshot of a deployment with settingsEnvironments, not versions
Custom domain API mappingapi.harbourline.example/v1 → API A, stage prodSeparate APIs per major version; hides stage names; multi-level keys (accounts/v1) need apigatewayv2 create-api-mapping
Routing rules (REST APIs)Up to two header conditions and one base-path condition per rule, evaluated by priorityHeader-based versioning (x-api-version: 2*) or gradual migration; not supported when a domain maps both REST and HTTP APIs
Canary settings (REST stages)Percentage of traffic to a new deploymentSafe rollout inside one version

Understand CORS before configuring it

Origin = scheme + host + port. https://app.harbourline.example and https://api.harbourline.example are different origins.

A request is simple (no preflight) only if the method is GET, HEAD or POST, the only manually set headers are CORS-safelisted ones (Accept, Accept-Language, Content-Language, Content-Type, and Range with a single range), and Content-Type is application/x-www-form-urlencoded, multipart/form-data or text/plain. Anything else is preflighted.

Consequence for banking APIs: every call with Authorization: Bearer ... or Content-Type: application/json or Idempotency-Key is preflighted. Plan for it.

The preflight is an OPTIONS request with Origin, Access-Control-Request-Method and Access-Control-Request-Headers. It carries no credentials (no cookies, no Authorization header), so it must not require authentication. The server answers with:

Response headerMeaning
Access-Control-Allow-OriginThe one origin allowed (or *)
Access-Control-Allow-MethodsMethods allowed for the actual request
Access-Control-Allow-HeadersRequest headers allowed (authorization, content-type, idempotency-key)
Access-Control-Allow-Credentialstrue if cookies/HTTP auth may be sent
Access-Control-Max-AgeSeconds the browser may cache the preflight (browsers cap it)
Access-Control-Expose-HeadersResponse headers scripts may read beyond the safelisted ones (Location, Retry-After, X-Correlation-Id)
Vary: OriginRequired when the allowed origin is chosen dynamically, so caches do not mix responses

Credentials and wildcards: for credentialed requests, * is forbidden in Allow-Origin, Allow-Headers, Allow-Methods and Expose-Headers. Name the origin explicitly.

What CORS is not: a server-side access control. The browser still sends simple requests and the server still processes them; CORS only decides whether the script may read the response. curl, Postman, mobile apps and servers ignore CORS entirely. Authentication, authorisation, CSRF defences (when using cookies) and WAF rules protect the API.

Configure CORS in exactly one owner

SetupWho answers the preflightWho adds headers to actual responsesError responses (401, 403, 429, 5xx from the gateway)
HTTP API with CORS configuredAPI Gateway, automatically (no OPTIONS route needed)API Gateway — it ignores CORS headers from your integrationAPI Gateway adds them
REST API, non-proxy integrationAn OPTIONS method with a mock integration returning Access-Control-Allow-*Integration response header mappings on each methodAdd headers to gateway responses (DEFAULT_4XX, DEFAULT_5XX)
REST API, Lambda/HTTP proxy integration (the module project)OPTIONS mock method without authorizer (CDK DefaultCorsPreflightOptions creates them)Your backend (ASP.NET Core CORS middleware), because proxy integrations have no integration responseGateway responses DEFAULT_4XX/DEFAULT_5XX
ASP.NET Core only (local, ECS behind ALB)CORS middlewareCORS middlewareYour app

Two REST API traps: enabling CORS on a resource in the console does not apply to child resources, and you must redeploy the API for changes to take effect. One HTTP API trap: with a $default route protected by an authorizer, preflights hit the authorizer; add an OPTIONS /{proxy+} route without authorization.

Why gateway responses matter: when API Gateway itself rejects a request (expired token → 401, throttling → 429), the response comes from the gateway, not your code. Without Access-Control-Allow-Origin on it, the browser hides the real error and the front-end team sees only "CORS error" — and spends a day debugging the wrong thing.

Preflight, step by step

AWS Console instructions

  • Validators and models (REST API): Console → API Gateway → APIs → (API) → Models → Create model (name, content type application/json, paste the draft-4 schema). Then Resources → (method) → Method request → Edit → Request validator: Validate body, query string parameters, and headers; under Request body add the model; under HTTP request headers add Idempotency-Key as required. Deploy API.
  • Customise validation errors: Gateway responses → Bad Request Body → Edit: add a response header Access-Control-Allow-Origin and a body template using $context.error.validationErrorString.
  • CORS (REST API): Resources → select resource → Enable CORS. Tick the methods (OPTIONS must be ticked), set Access-Control-Allow-Origin to your exact origin, optionally select Default 4XX and Default 5XX gateway responses, Save, then Deploy API. Repeat for child resources.
  • CORS (HTTP API): APIs → (HTTP API) → CORS → Configure: Allow origins, methods, headers, expose headers, max age, credentials. Changes apply to the stage automatically if auto-deploy is on.

AWS CLI

A throwaway REST API with a mock integration demonstrates validation, a customised BAD_REQUEST_BODY response and CORS without any backend. Run in Git Bash (the JSON quoting is simpler than in PowerShell). Save the schema above as statement-request.schema.json and these two files:

cors-integration-response.json
{
  "method.response.header.Access-Control-Allow-Origin": "'https://app.harbourline.example'",
  "method.response.header.Access-Control-Allow-Methods": "'OPTIONS,POST'",
  "method.response.header.Access-Control-Allow-Headers": "'Authorization,Content-Type,Idempotency-Key,X-Correlation-Id'",
  "method.response.header.Access-Control-Max-Age": "'600'"
}
cors-gateway-response.json
{
  "gatewayresponse.header.Access-Control-Allow-Origin": "'https://app.harbourline.example'",
  "gatewayresponse.header.Vary": "'Origin'"
}
P="--profile learn-sandbox --region us-east-1"

# 1. Create the API with mandatory tags, find the root resource, add /statement-requests.
API_ID=$(aws apigateway create-rest-api --name hl-m04-validation-demo \
  --endpoint-configuration types=REGIONAL \
  --tags Project=cea-lab,Lab=m04-validation,Environment=learn,Owner=your-name \
  --query id --output text $P)
ROOT_ID=$(aws apigateway get-resources --rest-api-id $API_ID --query "items[?path=='/'].id" --output text $P)
RES_ID=$(aws apigateway create-resource --rest-api-id $API_ID --parent-id $ROOT_ID \
  --path-part statement-requests --query id --output text $P)

# 2. Model + validator (body and parameters).
aws apigateway create-model --rest-api-id $API_ID --name StatementRequestBody \
  --content-type application/json --schema file://statement-request.schema.json $P
VAL_ID=$(aws apigateway create-request-validator --rest-api-id $API_ID --name body-and-params \
  --validate-request-body --validate-request-parameters --query id --output text $P)

# 3. POST: validator, model, required Idempotency-Key header, mock integration returning 202.
aws apigateway put-method --rest-api-id $API_ID --resource-id $RES_ID --http-method POST \
  --authorization-type NONE --request-validator-id $VAL_ID \
  --request-models application/json=StatementRequestBody \
  --request-parameters method.request.header.Idempotency-Key=true $P
aws apigateway put-integration --rest-api-id $API_ID --resource-id $RES_ID --http-method POST \
  --type MOCK --request-templates '{"application/json":"{\"statusCode\": 202}"}' $P
aws apigateway put-method-response --rest-api-id $API_ID --resource-id $RES_ID --http-method POST \
  --status-code 202 --response-parameters method.response.header.Access-Control-Allow-Origin=false $P
aws apigateway put-integration-response --rest-api-id $API_ID --resource-id $RES_ID --http-method POST \
  --status-code 202 --selection-pattern "" \
  --response-parameters "{\"method.response.header.Access-Control-Allow-Origin\":\"'https://app.harbourline.example'\"}" $P

# 4. OPTIONS preflight: no authorization, mock integration, CORS headers.
aws apigateway put-method --rest-api-id $API_ID --resource-id $RES_ID --http-method OPTIONS \
  --authorization-type NONE $P
aws apigateway put-integration --rest-api-id $API_ID --resource-id $RES_ID --http-method OPTIONS \
  --type MOCK --passthrough-behavior NEVER \
  --request-templates '{"application/json":"{\"statusCode\": 200}"}' $P
aws apigateway put-method-response --rest-api-id $API_ID --resource-id $RES_ID --http-method OPTIONS \
  --status-code 200 --response-parameters \
  method.response.header.Access-Control-Allow-Origin=false,method.response.header.Access-Control-Allow-Methods=false,method.response.header.Access-Control-Allow-Headers=false,method.response.header.Access-Control-Max-Age=false $P
aws apigateway put-integration-response --rest-api-id $API_ID --resource-id $RES_ID --http-method OPTIONS \
  --status-code 200 --selection-pattern "" --response-parameters file://cors-integration-response.json $P

# 5. Gateway responses: CORS headers on gateway errors, and a problem-details body for validation failures.
aws apigateway put-gateway-response --rest-api-id $API_ID --response-type DEFAULT_4XX \
  --response-parameters file://cors-gateway-response.json $P
aws apigateway put-gateway-response --rest-api-id $API_ID --response-type DEFAULT_5XX \
  --response-parameters file://cors-gateway-response.json $P
aws apigateway put-gateway-response --rest-api-id $API_ID --response-type BAD_REQUEST_BODY \
  --status-code 400 --response-parameters file://cors-gateway-response.json \
  --response-templates '{"application/json":"{\"type\":\"https://api.harbourline.example/problems/validation\",\"title\":\"Request body failed validation\",\"status\":400,\"detail\":\"$context.error.validationErrorString\"}"}' $P

# 6. Deploy to a stage and test.
aws apigateway create-deployment --rest-api-id $API_ID --stage-name test $P
URL="https://$API_ID.execute-api.us-east-1.amazonaws.com/test"

curl -i -X OPTIONS "$URL/statement-requests" -H "Origin: https://app.harbourline.example" \
  -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: content-type,idempotency-key"
curl -i -X POST "$URL/statement-requests" -H "Content-Type: application/json" -H "Idempotency-Key: 8c1e5a5e4f6a" \
  -d '{"fromDate":"2026-10-01","toDate":"2026-10-31","format":"pdf"}'                                   # 202
curl -i -X POST "$URL/statement-requests" -H "Content-Type: application/json" -H "Idempotency-Key: 8c1e5a5e4f6a" \
  -d '{"fromDate":"2026-10-01","toDate":"2026-10-31","format":"pdf","customerId":"CUS-00067890"}'      # 400 body
curl -i -X POST "$URL/statement-requests" -H "Content-Type: application/json" \
  -d '{"fromDate":"2026-10-01","toDate":"2026-10-31","format":"pdf"}'                                   # 400 params

For an HTTP API, CORS is one command (API id from aws apigatewayv2 get-apis):

aws apigatewayv2 update-api --api-id abc123 --cors-configuration \
  AllowOrigins=https://app.harbourline.example,AllowMethods=GET,POST,AllowHeaders=authorization,content-type,idempotency-key,ExposeHeaders=location,retry-after,x-correlation-id,MaxAge=600 \
  --profile learn-sandbox --region us-east-1

Infrastructure as Code

The module project's CDK stack uses DefaultCorsPreflightOptions, which creates an unauthenticated OPTIONS mock method on every resource, and adds CORS headers to the default gateway responses. The ASP.NET Core app adds headers to the actual (proxied) responses from the same configuration value.

using System.Collections.Generic;
using Amazon.CDK.AWS.APIGateway;
using Constructs;

namespace Harbourline.AccountInformation.Infra;

public static class ApiValidationAndCors
{
    public static readonly string[] AllowedOrigins = ["https://app.harbourline.example"];

    public static RestApi CreateApi(Construct scope)
    {
        var api = new RestApi(scope, "AccountInformationApi", new RestApiProps
        {
            RestApiName = "hl-m04-account-information",
            DefaultCorsPreflightOptions = new CorsOptions
            {
                AllowOrigins = AllowedOrigins,
                AllowMethods = ["GET", "POST", "OPTIONS"],
                AllowHeaders = ["Authorization", "Content-Type", "Idempotency-Key", "X-Correlation-Id"],
                MaxAge = Amazon.CDK.Duration.Minutes(10),
            },
        });

        // CORS headers on errors produced by API Gateway itself (401, 403, 429, 5xx).
        foreach (var type in new[] { ResponseType_.DEFAULT_4XX, ResponseType_.DEFAULT_5XX })
        {
            api.AddGatewayResponse($"Cors{type.ResponseType}", new GatewayResponseOptions
            {
                Type = type,
                ResponseHeaders = new Dictionary<string, string>
                {
                    ["Access-Control-Allow-Origin"] = $"'{AllowedOrigins[0]}'",
                    ["Vary"] = "'Origin'",
                },
            });
        }

        var validator = api.AddRequestValidator("BodyAndParams", new RequestValidatorOptions
        {
            RequestValidatorName = "body-and-params",
            ValidateRequestBody = true,
            ValidateRequestParameters = true,
        });

        var model = api.AddModel("StatementRequestBody", new ModelOptions
        {
            ContentType = "application/json",
            ModelName = "StatementRequestBody",
            Schema = new JsonSchema
            {
                Schema = JsonSchemaVersion.DRAFT4,
                Type = JsonSchemaType.OBJECT,
                AdditionalProperties = false,
                Required = ["fromDate", "toDate", "format"],
                Properties = new Dictionary<string, IJsonSchema>
                {
                    ["fromDate"] = new JsonSchema { Type = JsonSchemaType.STRING, Pattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" },
                    ["toDate"] = new JsonSchema { Type = JsonSchemaType.STRING, Pattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" },
                    ["format"] = new JsonSchema { Type = JsonSchemaType.STRING, Enum = ["pdf", "csv"] },
                },
            },
        });

        // The method itself (Lambda proxy, Cognito authorizer, scopes) is created in AccountInformationStack:
        // pass RequestValidator = validator, RequestModels = { ["application/json"] = model } and
        // RequestParameters = { ["method.request.header.Idempotency-Key"] = true } in its MethodOptions.
        _ = validator;
        _ = model;
        return api;
    }
}

ResponseType_ (with a trailing underscore) is how the CDK's C# bindings name the gateway response type class, to avoid a clash with a property; ⚠ VERIFY the exact class name against your Amazon.CDK.Lib version and adjust if the compiler suggests otherwise.

Complete code

Program.cs (validation and CORS excerpt)
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

// 1. Small, explicit body limit for this API (Kestrel; on Lambda the gateway and model limits apply).
builder.WebHost.ConfigureKestrel(k => k.Limits.MaxRequestBodySize = 16 * 1024);

// 2. Strict JSON: unknown members such as "customerId" fail binding instead of being ignored.
builder.Services.ConfigureHttpJsonOptions(o =>
    o.SerializerOptions.UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow);

// 3. Built-in minimal API validation (.NET 10) + problem details for every error.
builder.Services.AddValidation();
builder.Services.AddProblemDetails();

// 4. One named CORS policy, origins from configuration (the CDK stack reads the same value).
var origins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];
builder.Services.AddCors(options => options.AddPolicy("HarbourlineWeb", policy => policy
    .WithOrigins(origins)
    .WithMethods("GET", "POST")
    .WithHeaders("Authorization", "Content-Type", "Idempotency-Key", "X-Correlation-Id")
    .WithExposedHeaders("Location", "Retry-After", "X-Correlation-Id", "Idempotent-Replayed")
    .SetPreflightMaxAge(TimeSpan.FromMinutes(10))));

var app = builder.Build();

app.UseExceptionHandler();
app.UseStatusCodePages();
app.UseCors();                 // before authentication, so preflights are answered without a token
// app.UseAuthentication(); app.UseAuthorization();  (see the Cognito and JWT lessons)

var v1 = app.MapGroup("/v1").RequireCors("HarbourlineWeb");

v1.MapPost("/accounts/{accountId}/statement-requests", (string accountId, StatementRequestBody body) =>
{
    var errors = StatementRequestRules.Check(body);
    if (errors.Count > 0)
    {
        return Results.ValidationProblem(errors, statusCode: StatusCodes.Status422UnprocessableEntity,
            type: "https://api.harbourline.example/problems/invalid-statement-period");
    }

    var id = $"STR-{Guid.CreateVersion7():N}";
    return Results.Accepted($"/v1/statement-requests/{id}", new { statementRequestId = id, status = "queued" });
});

app.Run();

// Request record: only what the client may set. No CustomerId, Status or CreatedAt.
public sealed record StatementRequestBody(
    [property: Required] DateOnly? FromDate,
    [property: Required] DateOnly? ToDate,
    [property: Required, AllowedValues("pdf", "csv")] string? Format);

public static class StatementRequestRules
{
    // Business rules → 422. Shape problems were already rejected with 400 by binding and AddValidation.
    public static Dictionary<string, string[]> Check(StatementRequestBody body)
    {
        var errors = new Dictionary<string, string[]>();
        if (body.FromDate is { } from && body.ToDate is { } to)
        {
            if (to < from)
            {
                errors["toDate"] = ["toDate must be on or after fromDate."];
            }
            else if (to.DayNumber - from.DayNumber > 366)
            {
                errors["toDate"] = ["A statement can cover at most 12 months."];
            }

            if (to > DateOnly.FromDateTime(DateTime.UtcNow))
            {
                errors["toDate"] = ["toDate cannot be in the future."];
            }
        }
        return errors;
    }
}
appsettings.json (excerpt)
{
  "Cors": {
    "AllowedOrigins": [ "https://app.harbourline.example" ]
  }
}

Code explained line by line

  1. MaxRequestBodySize = 16 * 1024 caps request bodies at 16 KB when Kestrel serves the request (local, ECS). Larger requests get 413 before binding.
  2. UnmappedMemberHandling.Disallow makes System.Text.Json throw on unknown properties; minimal API binding turns that into a 400, and AddProblemDetails + UseStatusCodePages give it a problem-details body.
  3. AddValidation() enables the source-generated validator for minimal API parameters; the [Required] and [AllowedValues] attributes on StatementRequestBody are checked before the handler runs.
  4. [property: Required] targets the generated property of a positional record. DateOnly? lets "missing" be detected as null rather than defaulting to 0001-01-01.
  5. AddCors(...AddPolicy("HarbourlineWeb", ...)) defines one named policy: explicit origins from configuration, explicit methods and headers, the response headers scripts may read, and a 10-minute preflight cache.
  6. No AllowCredentials(): the API uses bearer tokens in a header, not cookies, so credentialed CORS is unnecessary. If you ever add cookies, you must list exact origins (never AllowAnyOrigin()) and add CSRF protection.
  7. app.UseCors() runs before authentication, so OPTIONS preflights (which carry no token) are answered instead of rejected with 401.
  8. RequireCors("HarbourlineWeb") applies the policy to the /v1 group only; health checks and /openapi are not CORS-enabled.
  9. StatementRequestRules.Check holds cross-field business rules and returns Results.ValidationProblem(..., statusCode: 422), following Harbourline's 400-for-shape, 422-for-rules convention.
  10. The handler never receives a customer id from the client; the module project resolves it from the token.

Security considerations

  • Validate at every layer; trust none. Gateway validation is an optimisation and a filter, not a control.
  • Mass assignment: separate request records, additionalProperties: false in gateway models, UnmappedMemberHandling.Disallow in the app, and server-set fields never bound from input (OWASP API3:2023).
  • Never reflect the Origin header blindly, especially with Access-Control-Allow-Credentials: true. Allow-list exact origins; include Vary: Origin.
  • No null origin. Sandboxed iframes and local files send Origin: null; allowing it lets any such page read responses.
  • Do not leak details in validation errors: $context.error.validationErrorString is fine for field names and constraints, but never echo full request bodies (they may contain personal data) into errors or logs.
  • CORS does not stop CSRF for cookie-authenticated endpoints; bearer tokens in headers are not sent automatically by browsers, which is one reason banking APIs prefer them.

⚠ Learning shortcut — not for production

The CLI demo creates a REST API with no authorizer and a public test stage so you can see validation and CORS without Cognito. It returns only static mock responses, but delete it the same day. In production every method except OPTIONS has an authorizer, the stage has AWS WAF, throttling and access logging, and allowed origins come from configuration reviewed by the security team — different per environment, never *.

Banking use case

Harbourline's new web banking app (https://app.harbourline.example) calls the Account Information API from the browser with access tokens obtained through Cognito's authorization code flow with PKCE. The REST API answers preflights with OPTIONS mock methods created by CDK; the ASP.NET Core app adds Access-Control-Allow-Origin to proxied responses and exposes Location so the app can poll statement requests. Gateway responses carry CORS headers, so when a token expires the app sees a real 401 and silently refreshes the token instead of showing a "network error". Partners and the mobile app ignore CORS entirely — their protection is OAuth scopes, WAF rules and throttling. Validation errors list field names but never echo values, a choice the data protection officer approved under UK GDPR data minimisation.

Common mistakes

  • Relying only on gateway validation → "API Gateway already checks it" → HTTP APIs, local runs and misconfigured content types skip it; validate in code.
  • Model attached to application/json but the client sends application/json; charset=utf-8 → validation silently skipped in some setups → test with your real clients, or use $default to always validate (and passthroughBehavior NEVER to reject unknown types).
  • Expecting parameter validation to check formats → it only checks presence → validate types and patterns in code or via the model.
  • Authorizer on OPTIONS → preflights carry no token → 401 on every browser call; leave OPTIONS unauthenticated.
  • No CORS headers on gateway error responses → front end sees "CORS error" instead of 401/429 → configure DEFAULT_4XX/DEFAULT_5XX.
  • * with credentials, or reflecting any Origin → copy-paste fixes → browsers reject the former, attackers love the latter.
  • Configuring CORS in both HTTP API and the backend → duplicate or conflicting headers; HTTP API ignores backend CORS headers anyway → pick one owner.
  • Forgetting to redeploy a REST API after changing CORS or validators → old behaviour persists.

Troubleshooting

SymptomLikely causeFix
Browser: "Response to preflight request doesn't pass access control check"OPTIONS not configured, requires auth, or missing a requested header in Allow-HeadersAdd/unauthenticate OPTIONS; include every header the client sends (lower-case comparison is fine)
Browser shows CORS error but curl shows 401 or 429Gateway response lacks CORS headersAdd Access-Control-Allow-Origin to DEFAULT_4XX/DEFAULT_5XX and redeploy
{"message": "Invalid request body"} with no detailDefault BAD_REQUEST_BODY gateway responseCustomise it with $context.error.validationErrorString; check execution logs
Invalid bodies reach Lambda anywayNo validator on the method, or no model for the request's content typeAttach validator and model (or $default), redeploy
{"message":"Missing required request parameters: [Idempotency-Key]"}Parameter marked required and absentExpected; the client must send it
Unknown JSON fields accepted in ASP.NET CoreDefault UnmappedMemberHandling.SkipSet Disallow in ConfigureHttpJsonOptions
AddValidation() does nothingTypes in another assembly, or metadata not generatedCall AddValidation from that assembly (extension method); add a test that posts an invalid body
CORS works on /v1/accounts but not /v1/accounts/{accountId}Console CORS enablement is not recursiveEnable on each resource, or use CDK DefaultCorsPreflightOptions
413 from API GatewayBody over 10 MBPaginate or upload large files to S3 with presigned URLs

Cost and cleanup

Cost: effectively $0. The ASP.NET Core parts run locally. The CLI demo is a REST API with mock integrations: REST API calls cost $3.50 per million in us-east-1 (checked 2026-11-17), and accounts eligible for the API Gateway free tier get 1 million REST calls per month for 12 months, so a dozen test calls cost nothing measurable. There is no backend, no Lambda and no WAF in the demo.

# Delete the demo API (deletes its stage, methods, models, validators and gateway responses).
aws apigateway delete-rest-api --rest-api-id $API_ID --profile learn-sandbox --region us-east-1

# Confirm nothing tagged for the course remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab --profile learn-sandbox --region us-east-1

Exercises

  • 🟢 Guided: Build the CLI demo. Run the four curl commands and record each status code and body. Then remove the DEFAULT_4XX gateway response, redeploy, and call the API from a browser console on any https page with fetch — observe how the browser reports the 400.
  • 🟡 Challenge: In the ASP.NET Core app, write xUnit tests with WebApplicationFactory that prove: unknown member → 400; missing format → 400 with an errors.Format entry; toDate before fromDate → 422; preflight from https://app.harbourline.example → 204 with the right Access-Control-Allow-* headers; preflight from https://evil.example → no Access-Control-Allow-Origin.
  • 🔴 Live problem: After moving from a REST API to an HTTP API to save cost, the security team's scan shows that request bodies with extra fields and 5 MB payloads now reach the Lambda function, and the web app's preflights fail with 401. Write the remediation plan.

Assignment

Add a docs/input-validation-and-cors.md to your portfolio: a table of every input of the Account Information API (path, query, header, body field) with the layer(s) that validate it and the status code on failure; your CORS policy (origins per environment, methods, headers, exposed headers, credentials decision) with the reasoning; and your API versioning plan on API Gateway (paths, stages, mappings).

Solutions

Knowledge check

Interview questions

  • "Where do you validate input in an AWS API?" — In layers: gateway models/validators on REST APIs for cheap early rejection, strict binding and validation in the app (always), domain and authorisation rules in the service. The app never assumes the gateway ran.
  • "Explain a CORS preflight." — For non-simple requests the browser sends OPTIONS with Origin, Access-Control-Request-Method and -Headers; the server returns the allowed origin, methods, headers and max age; only then does the browser send the real request and, if allowed, expose the response to the script.
  • "Why can't you use * with credentials?" — The CORS rules forbid wildcards in Allow-Origin, Allow-Headers, Allow-Methods and Expose-Headers for credentialed requests; you must name the origin, and you should allow-list rather than reflect.
  • "What is mass assignment and how do you prevent it in .NET?" — Binding client input onto fields the client should not control. Use dedicated request records, reject unknown members, set server-owned fields in code, and use additionalProperties: false in schemas.
  • "How do you version an API on API Gateway?" — /v1 paths or separate APIs mapped by base path on a custom domain; routing rules for header-based versions on REST APIs; stages only for environments.

Certification practice

Completion checklist

  • I can list the validation layers and what each can and cannot check
  • I built and deleted the CLI demo (or reviewed it) and saw validator, gateway response and CORS behaviour
  • My ASP.NET Core API rejects unknown members and oversize bodies, and validates rules with 400/422 consistently
  • I can explain a preflight, the credentials-and-wildcard rule, and why CORS is not server security
  • The tag check shows nothing with Project=cea-lab remaining

Key takeaways

  • Validate in layers; the application layer is mandatory, the gateway layer is an optimisation (and absent on HTTP APIs).
  • REST API models are JSON Schema draft 4; parameter validation checks presence only; use additionalProperties: false.
  • Defeat mass assignment with dedicated request records and UnmappedMemberHandling.Disallow.
  • Stages are environments; version with /v1, API mappings or routing rules.
  • CORS is a browser read-permission protocol: preflight for anything non-simple, explicit origins, no wildcards with credentials, CORS headers on gateway error responses too.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page