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.
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: falseandUnmappedMemberHandling.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
/v1paths, 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
- REST API design for banking (status codes, problem details)
- OpenAPI contracts and contract testing (models come from the contract)
- API Gateway: REST vs HTTP vs WebSocket (recommended)
- Tools: .NET 10 SDK, Git Bash (for the CLI section's quoting), AWS CLI v2 with the
learn-sandboxprofile
Why this matters in banking
Three real-world failure patterns:
- 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. - 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.
- 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
$defaultas the content type to always validate. - Failures return 400 with gateway response type
BAD_REQUEST_PARAMETERSorBAD_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 equivalent | What's different |
|---|---|---|
APIM validate-content / validate-parameters policies | REST API request validators + models | JSON Schema draft 4 only; parameter checks are presence-only |
APIM cors policy | HTTP API CORS configuration; REST API OPTIONS methods + response headers | REST APIs need you to wire OPTIONS and error responses yourself (or CDK does it) |
[ApiController] automatic 400 with ValidationProblemDetails | ASP.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, RequireCors | Unchanged; decide whether the gateway or the app owns CORS |
| APIM versions / revisions | /v1 resources, stages, custom-domain API mappings, routing rules | Stages are environments, not versions |
| Front Door / App Gateway WAF body inspection | AWS WAF on REST API stages (not HTTP APIs) | See API security |
Kestrel MaxRequestBodySize | Same — plus the gateway's 10 MB and Lambda's 6 MB ceilings | Set 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).
{
"$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
MaxRequestBodySizeto 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.Jsonskips unknown properties by default. SetUnmappedMemberHandling = JsonUnmappedMemberHandling.Disallowso{"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 theStatementRequestentity. The entity'sCustomerId,StatusandCreatedAtare 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
UnmappedMemberHandlingsetting 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
| Tool | What it is | Use it for |
|---|---|---|
/v1 resource prefix | Part of the resource tree in one API | Simple APIs where v1 and v2 share a backend |
Stage (dev, test, prod) | Named snapshot of a deployment with settings | Environments, not versions |
| Custom domain API mapping | api.harbourline.example/v1 → API A, stage prod | Separate 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 priority | Header-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 deployment | Safe 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 header | Meaning |
|---|---|
Access-Control-Allow-Origin | The one origin allowed (or *) |
Access-Control-Allow-Methods | Methods allowed for the actual request |
Access-Control-Allow-Headers | Request headers allowed (authorization, content-type, idempotency-key) |
Access-Control-Allow-Credentials | true if cookies/HTTP auth may be sent |
Access-Control-Max-Age | Seconds the browser may cache the preflight (browsers cap it) |
Access-Control-Expose-Headers | Response headers scripts may read beyond the safelisted ones (Location, Retry-After, X-Correlation-Id) |
Vary: Origin | Required 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
| Setup | Who answers the preflight | Who adds headers to actual responses | Error responses (401, 403, 429, 5xx from the gateway) |
|---|---|---|---|
| HTTP API with CORS configured | API Gateway, automatically (no OPTIONS route needed) | API Gateway — it ignores CORS headers from your integration | API Gateway adds them |
| REST API, non-proxy integration | An OPTIONS method with a mock integration returning Access-Control-Allow-* | Integration response header mappings on each method | Add 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 response | Gateway responses DEFAULT_4XX/DEFAULT_5XX |
| ASP.NET Core only (local, ECS behind ALB) | CORS middleware | CORS middleware | Your 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 addIdempotency-Keyas required. Deploy API. - Customise validation errors: Gateway responses → Bad Request Body → Edit: add a response header
Access-Control-Allow-Originand 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-Originto 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:
{
"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'"
}{
"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 paramsFor 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-1Infrastructure 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
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;
}
}{
"Cors": {
"AllowedOrigins": [ "https://app.harbourline.example" ]
}
}Code explained line by line
MaxRequestBodySize = 16 * 1024caps request bodies at 16 KB when Kestrel serves the request (local, ECS). Larger requests get 413 before binding.UnmappedMemberHandling.DisallowmakesSystem.Text.Jsonthrow on unknown properties; minimal API binding turns that into a 400, andAddProblemDetails+UseStatusCodePagesgive it a problem-details body.AddValidation()enables the source-generated validator for minimal API parameters; the[Required]and[AllowedValues]attributes onStatementRequestBodyare checked before the handler runs.[property: Required]targets the generated property of a positional record.DateOnly?lets "missing" be detected asnullrather than defaulting to0001-01-01.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.- 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 (neverAllowAnyOrigin()) and add CSRF protection. app.UseCors()runs before authentication, so OPTIONS preflights (which carry no token) are answered instead of rejected with 401.RequireCors("HarbourlineWeb")applies the policy to the/v1group only; health checks and/openapiare not CORS-enabled.StatementRequestRules.Checkholds cross-field business rules and returnsResults.ValidationProblem(..., statusCode: 422), following Harbourline's 400-for-shape, 422-for-rules convention.- 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: falsein gateway models,UnmappedMemberHandling.Disallowin the app, and server-set fields never bound from input (OWASP API3:2023). - Never reflect the
Originheader blindly, especially withAccess-Control-Allow-Credentials: true. Allow-list exact origins; includeVary: Origin. - No
nullorigin. Sandboxed iframes and local files sendOrigin: null; allowing it lets any such page read responses. - Do not leak details in validation errors:
$context.error.validationErrorStringis 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/jsonbut the client sendsapplication/json; charset=utf-8→ validation silently skipped in some setups → test with your real clients, or use$defaultto always validate (andpassthroughBehaviorNEVERto 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
| Symptom | Likely cause | Fix |
|---|---|---|
| Browser: "Response to preflight request doesn't pass access control check" | OPTIONS not configured, requires auth, or missing a requested header in Allow-Headers | Add/unauthenticate OPTIONS; include every header the client sends (lower-case comparison is fine) |
| Browser shows CORS error but curl shows 401 or 429 | Gateway response lacks CORS headers | Add Access-Control-Allow-Origin to DEFAULT_4XX/DEFAULT_5XX and redeploy |
{"message": "Invalid request body"} with no detail | Default BAD_REQUEST_BODY gateway response | Customise it with $context.error.validationErrorString; check execution logs |
| Invalid bodies reach Lambda anyway | No validator on the method, or no model for the request's content type | Attach validator and model (or $default), redeploy |
{"message":"Missing required request parameters: [Idempotency-Key]"} | Parameter marked required and absent | Expected; the client must send it |
| Unknown JSON fields accepted in ASP.NET Core | Default UnmappedMemberHandling.Skip | Set Disallow in ConfigureHttpJsonOptions |
AddValidation() does nothing | Types in another assembly, or metadata not generated | Call 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 recursive | Enable on each resource, or use CDK DefaultCorsPreflightOptions |
413 from API Gateway | Body over 10 MB | Paginate 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-1Exercises
- 🟢 Guided: Build the CLI demo. Run the four curl commands and record each status code and body. Then remove the
DEFAULT_4XXgateway response, redeploy, and call the API from a browser console on anyhttpspage withfetch— observe how the browser reports the 400. - 🟡 Challenge: In the ASP.NET Core app, write xUnit tests with
WebApplicationFactorythat prove: unknown member → 400; missingformat→ 400 with anerrors.Formatentry;toDatebeforefromDate→ 422; preflight fromhttps://app.harbourline.example→ 204 with the rightAccess-Control-Allow-*headers; preflight fromhttps://evil.example→ noAccess-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
Expected: OPTIONS → 200 with the four Access-Control-* headers; valid POST → 202 with Access-Control-Allow-Origin; extra customerId → 400 with your problem-details body and a detail naming the disallowed property; missing Idempotency-Key → 400 "Missing required request parameters". Without the DEFAULT_4XX CORS header the browser console reports a CORS failure and fetch rejects with a TypeError — the script cannot see the 400 at all. Why: gateway-generated errors bypass your integration's headers.
For the preflight tests, send OPTIONS with Origin and Access-Control-Request-Method: POST headers through factory.CreateClient(); the CORS middleware answers with 204 No Content and the allowed headers for an allowed origin, and omits Access-Control-Allow-Origin for a disallowed one (the request still "succeeds" — the browser is the one that blocks). Assert the validation responses by deserialising HttpValidationProblemDetails and checking Errors keys. Why: CORS and validation are configuration-heavy and silently regress; tests make them part of the contract.
HTTP APIs have no request validation, so (1) move every check into the app: UnmappedMemberHandling.Disallow, AddValidation() or explicit validators, and a body-size check (Lambda's 6 MB limit is far above what this endpoint needs — reject large Content-Length early in middleware). (2) For preflights: with an authorizer on the $default route, add an OPTIONS /{proxy+} route with no authorization, configure CORS on the HTTP API (which then answers preflights and ignores backend CORS headers), and remove CORS from the app to avoid confusion. (3) Note what else was lost: AWS WAF cannot be attached to HTTP APIs, so either put CloudFront with WAF in front or reconsider the move. Document the cost saving against the controls lost and get security sign-off. Why: REST and HTTP APIs differ in features, not just price.
Knowledge check
Answer: REST APIs. Models use JSON Schema draft 4. HTTP APIs do not support request validation.
Answer: Authorization is not a CORS-safelisted request header (and Content-Type: application/json is not a safelisted value), so the request is not simple; the browser sends an OPTIONS preflight first.
Answer: No. It tells browsers whether scripts from another origin may read responses. Non-browser clients ignore it, and simple requests still reach the server. Authentication, authorisation, WAF and CSRF defences protect the API.
Answer: The backend (for example ASP.NET Core CORS middleware), because proxy integrations have no integration response to map headers. Preflights are answered by an OPTIONS mock method, and gateway-generated errors need CORS headers on gateway responses.
Answer: System.Text.Json skips them. Set JsonSerializerOptions.UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow (for minimal APIs via ConfigureHttpJsonOptions) to reject them with 400.
Answer: 10 MB for both API types; 6 MB each for request and response for synchronous Lambda invocations. Set far smaller limits in your own code.
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-Methodand-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 inAllow-Origin,Allow-Headers,Allow-MethodsandExpose-Headersfor 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: falsein schemas. - "How do you version an API on API Gateway?" —
/v1paths 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
A developer wants Amazon API Gateway to reject requests whose JSON body is missing required fields before the backend Lambda function is invoked, reducing cost. The API is currently an HTTP API. What should the developer do?
A. Enable request validation on the HTTP API route
B. Migrate the API to a REST API and configure a request validator with a JSON Schema model on the method
C. Add a Lambda authorizer that parses the body
D. Configure CORS to allow only application/json
Answer: B. Request validators and models are a REST API feature; HTTP APIs do not support request validation, so A is impossible. C misuses authorizers (and REQUEST authorizers on REST APIs do not receive the body). D affects browsers only.
A single-page app calls a REST API that uses a Cognito user pool authorizer and Lambda proxy integrations. Successful calls work. When a token expires, the browser console reports a CORS error instead of a 401, so the app cannot refresh the token. What is the fix?
A. Add Access-Control-Allow-Origin to the DEFAULT_4XX gateway response and redeploy
B. Add CORS headers in the Lambda function's responses
C. Enable CORS on the Cognito user pool
D. Increase the authorizer cache TTL
Answer: A. The 401 is generated by API Gateway, not by Lambda, so B does not affect it. C is not how CORS works for the API. D changes caching, not headers.
A security review finds that an API returns Access-Control-Allow-Origin equal to whatever Origin header the request contains, together with Access-Control-Allow-Credentials: true. The API uses session cookies. What is the risk and the best remediation?
A. No risk, because CORS is only a browser feature
B. Any website can make a logged-in user's browser call the API and read the responses; replace reflection with an explicit allow-list of trusted origins and add CSRF protection
C. The risk is denial of service; add a rate-based AWS WAF rule
D. Replace the header value with *
Answer: B. Reflecting origins with credentials lets attacker pages read authenticated responses. A ignores that the victim's browser carries the cookies. C addresses a different threat. D is rejected by browsers for credentialed requests and would still be inappropriate.
A company exposes api.example.com with an API Gateway REST API for version 1. Version 2 is a separate REST API. Clients must select the version with an x-api-version header, without changing URLs. Which feature meets the requirement with the least custom code?
A. Stage variables B. Custom domain routing rules with a header condition that invokes the stage of the version 2 API C. A Lambda authorizer that redirects requests D. Two API keys in different usage plans
Answer: B. Routing rules on a custom domain can match header conditions and invoke a REST API stage. A configures a stage but cannot choose between APIs by header. C and D are not routing mechanisms.
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-labremaining
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
- Request validation for REST APIs in API Gateway and set up basic request validation
- Data models for REST APIs
- Choose between REST APIs and HTTP APIs
- CORS for REST APIs, enable CORS in the console and CORS for HTTP APIs
- Gateway response types
- API mappings and routing rules for custom domain names
- Validation in ASP.NET Core (.NET 10)
- MDN: Cross-Origin Resource Sharing (CORS)
- OWASP API3:2023 Broken Object Property Level Authorization
- Lambda quotas (invocation payload) and REST API quotas
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.
IAM/SigV4 authorisation and mTLS for machine callers
Protect API Gateway APIs for machine-to-machine callers with IAM authorisation (SigV4), resource policies, private APIs and mutual TLS, and choose the right control for internal services and B2B partners.
Webhooks: send and receive safely with HMAC and replay protection
Receive partner webhooks on AWS with raw-body HMAC-SHA256 verification, timestamp tolerance, replay protection and fast acknowledgement, and send your own signed webhooks with retries, dead-letter queues and SSRF defences.