Module project: the Account Information API (Cognito, ownership checks, idempotency, throttling and WAF)
Run, attack and optionally deploy a .NET 10 Account Information API where each customer sees only their own accounts: Cognito access tokens and scopes, server-side customer mapping, validation, idempotent statement requests, ProblemDetails, correlation IDs, throttling and AWS WAF.
Assumes: .NET 10 LTS · ASP.NET Core 10 (JwtBearer 10.0.15) · AWS SDK for .NET v4 (AWSSDK.DynamoDBv2 4.1.0.2) · Amazon.Lambda.AspNetCoreServer.Hosting 2.2.1 · Microsoft.Extensions.Http.Resilience 10.11.0 · xUnit v3 4.0.3 · Amazon.CDK.Lib 2.277.0 · Cdklabs.CdkNag 3.0.2 · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this project you can:
- Run an ASP.NET Core 10 API locally with a local test token issuer, and run its 55 automated tests without an AWS account.
- Explain how the API separates operation-level authorisation (scopes, in policies) from object-level authorisation (does this customer own this account, in the data layer), and prove it with a second user.
- Show that "not yours" and "does not exist" are indistinguishable (404) so the API is not an account-enumeration oracle.
- Use the 400 versus 422 split: 400 for malformed input, 422 for well-formed input that breaks a business rule.
- Make the one write endpoint safe to retry with an
Idempotency-Key, and describe the DynamoDB conditional-write design behind it. - Read the CDK stack that puts Cognito, API Gateway, Lambda, DynamoDB and AWS WAF around the same binary, and deploy it for under an hour in the sandbox account, then tear it down.
- State the difference between API Gateway throttling, the in-app per-customer limiter and WAF rate-based rules, and why a bank wants all three.
This page is the module project for Module 4. It pulls together REST API design, OAuth 2.0, OIDC and JWTs, Cognito user pools, Request validation, CORS, Idempotency keys, Calling partner APIs, API security with WAF and the OWASP API Top 10 and API monitoring. It feeds Capstone 1.
Prerequisites
- The lessons above. Read at least the REST design, OAuth/JWT, idempotency and WAF lessons first.
- Docker Desktop. The .NET 10 SDK,
curlandjqare optional for the local part. - For the optional deployment (Parts 4 and 5): AWS CLI v2 with
learn-sandbox, Node.js with the AWS CDK CLI (npm i -g aws-cdk), the .NET 10 SDK, and CDK bootstrapped inus-east-1. Use only the sandbox account.
Why this matters in banking
An Account Information API is the first thing a bank exposes to a mobile app or a partner, and it is where the most expensive mistakes live. Broken object-level authorisation (OWASP API1) means customer A changes ACC-0000012345 to ACC-0000067890 in the URL and reads customer B's balance. A retried statement request that creates two statements, or a payment that is created twice, becomes a complaint. A missing rate limit lets one script scrape the whole customer base. And none of it can be diagnosed if you cannot connect a customer's error to a log line.
This project makes each control concrete, with a test that fails if the control is removed.
The idea in plain language
The API has five operations and a very simple rule: the customer is never something the client tells you. The client proves who it is with an access token. The server takes the token's sub (a stable user id from Cognito), looks it up in its own table to find the Harbourline customer id, and puts that id into every data query. If the account is not in that customer's list, the answer is "not found".
Analogy: a branch counter. The teller does not ask "which customer's accounts shall I show?" They look at your verified ID, find your record in their own system and only open your files. If you ask for a file number that is not yours, they say "I have no such file", not "that belongs to someone else".
What the AWS services do here
| Service | Role in the project | Local stand-in |
|---|---|---|
| Amazon Cognito user pool | Authenticates users (authorization code with PKCE), issues access tokens containing the scopes harbourline-accounts/accounts.read and harbourline-accounts/statements.write | POST /dev/tokens local test issuer (Development only) |
| Amazon API Gateway REST API | TLS edge, Cognito authoriser with scope checks per method, request validation, stage throttling, access logs | Kestrel on http://localhost:5080 |
AWS Lambda (dotnet10, arm64) | Runs the same ASP.NET Core binary through the Lambda hosting package | Kestrel |
| Amazon DynamoDB (on-demand, TTL) | Idempotency records, one item per scoped key | In-memory idempotency store |
| AWS WAF | Managed rule groups plus a rate-based rule per IP (Lab 4.7) | Not emulated |
| Amazon CloudWatch Logs and X-Ray | Structured JSON logs and traces | Console output |
Microsoft / Azure comparison
| You know (Microsoft/Azure) | In this project | What's different |
|---|---|---|
Azure API Management with validate-jwt | API Gateway Cognito authoriser with AuthorizationScopes, plus JwtBearer inside the app | Two layers: the gateway rejects early, the app re-validates because it must not trust the network |
| Entra ID app roles and scopes | Cognito resource server and custom scopes | Scopes are resource-server-id/scope-name; the access token has a scope claim and no aud |
| Azure Functions Premium behind APIM | One ASP.NET Core app on Lambda | The Lambda hosting package maps API Gateway events to ASP.NET Core requests; the same code runs on Kestrel |
| APIM rate-limit-by-key | Stage throttling plus RateLimiter partitioned by customer plus WAF | Gateway limits are per stage and method, WAF is per IP, only the app knows the customer |
| Azure Front Door WAF | AWS WAF web ACL on the API stage | Managed rule groups are named differently; association is by stage ARN |
| Cosmos DB with TTL for dedupe | DynamoDB conditional put with a TTL attribute | A conditional write is the atomic "claim" |
Architecture
Inside the app, a request passes through these layers in order:
The ordering is not accidental. CORS runs before authentication so a browser preflight needs no token. The rate limiter runs after authentication so it can use the customer as the key. Ownership is enforced at the very end, in the data layer, where the customerId argument comes from the validated token.
Step-by-step implementation
The project folder is labs/m04-account-information-api. Solution: Harbourline.AccountInformation.slnx.
openapi/ design contract (Lab 4.1)
src/Harbourline.AccountInformation.Api/ ASP.NET Core minimal API (Kestrel locally, Lambda in AWS)
tests/Harbourline.AccountInformation.Api.Tests/ 55 tests
infra/cdk/Harbourline.AccountInformation.Infra/ HlM04-AccountInformation and HlM04-Waf stacksPart 1: run the tests (free)
Run the tests in Docker
MSYS_NO_PATHCONV=1 docker run --rm --memory 3g \
-v "$PWD/labs/m04-account-information-api:/src" \
-v cea-nuget-m04:/root/.nuget/packages \
-w /src mcr.microsoft.com/dotnet/sdk:10.0 \
sh -c "dotnet test --solution Harbourline.AccountInformation.slnx; find . -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} +"Expected result (verified 2026-11-18 in Docker): total: 55, failed: 0, succeeded: 54, skipped: 1. The skipped test, Claim_complete_replay_against_real_table, talks to a real DynamoDB table and runs only with RUN_AWS_TESTS=1.
Map the tests to the requirements
| Requirement | Test class and examples |
|---|---|
| Authentication | AuthenticationTests: no token is 401 with a bearer challenge; an ID token is rejected (APIs accept access tokens only); a token for another app client, from another issuer, expired or tampered is rejected |
| Operation authorisation | A read-only token cannot request statements (403); a valid token for a user with no customer record is 403 |
| Object authorisation (second user) | OwnershipTests: each customer lists only their own accounts; someone else's account looks exactly like a missing one; someone else's transactions are not found; you cannot request a statement for someone else's account; a client-supplied customer id is ignored |
| Money representation | Account_response_carries_money_as_decimal_string_and_no_customer_id: balances are strings, never floating point, and the response does not leak the internal customer id |
| Validation | StatementRequestTests: missing or malformed Idempotency-Key is 400; shape errors (missing field, bad enum, malformed JSON, wrong date format) are 400; business rule errors (reversed range, more than 12 months, future date) are 422 |
| Pagination | TransactionPagingTests: walking all pages returns every transaction once, newest first; malformed pageSize, dates and cursors are 400; a cursor issued for other filters is rejected |
| Idempotency | Replay of the first response for same key and body; same key with different body is 422; the same key from another customer does not collide; the store tests cover the conditional put, replay, mismatch while in progress, reclaiming an abandoned lock and TTL expiry |
| Observability | CrossCuttingTests: caller correlation id echoed; unsafe ids replaced; X-Amzn-Trace-Id root used when no header; ProblemDetails carry correlation and trace ids |
| Throttling | The fourth request in the window is 429 with Retry-After, and other customers are unaffected |
| Resilience | CoreBankingResilienceTests: transient 503s are retried; 404 is not retried; a persistent failure opens the circuit and stops calling the core; the API returns 503 with Retry-After when the core is down |
Part 2: run it locally and try to break it (free)
Start the API
dotnet run --project src/Harbourline.AccountInformation.Api # http://localhost:5080, DevelopmentTwo fictional customers are seeded: sub-alice-0001 maps to CUS-00012345 (two GBP accounts) and sub-bob-0002 maps to CUS-00067890 (one EUR account).
Mint a token for Alice and call the API
# Mint a local test token for Alice (Development only: /dev/tokens does not exist in Production).
TOKEN=$(curl -s -X POST localhost:5080/dev/tokens -H "Content-Type: application/json" \
-d '{"subject":"sub-alice-0001","scopes":["harbourline-accounts/accounts.read","harbourline-accounts/statements.write"]}' | jq -r .access_token)
curl -s localhost:5080/v1/accounts -H "Authorization: Bearer $TOKEN" | jq
curl -s "localhost:5080/v1/accounts/ACC-0000012345/transactions?pageSize=5" -H "Authorization: Bearer $TOKEN" | jqAttack it as Alice
# Bob's account: expect 404 (the same answer as a nonexistent account).
curl -i localhost:5080/v1/accounts/ACC-0000067890 -H "Authorization: Bearer $TOKEN"
# A malformed id: also 404 (it cannot belong to anyone).
curl -i localhost:5080/v1/accounts/not-an-account -H "Authorization: Bearer $TOKEN"
# No token: 401.
curl -i localhost:5080/v1/accounts
# Bad page size: 400 ProblemDetails with an errors object.
curl -i "localhost:5080/v1/accounts/ACC-0000012345/transactions?pageSize=500" -H "Authorization: Bearer $TOKEN"Look at each response body. They are application/problem+json with a type, title, status, instance, a correlationId and a traceId. Copy a correlationId and find the same value in the JSON log line the API wrote to its console.
Replay the write
curl -i -X POST localhost:5080/v1/accounts/ACC-0000012345/statement-requests \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-H "Idempotency-Key: 3f1c9a52-6a8e-4c39-b5a5-0f6f2d9b7e11" \
-d '{"fromDate":"2026-10-01","toDate":"2026-10-31","format":"pdf"}'You should get 202 Accepted with a Location header. Send the identical command again: the same body returns with an idempotent-replay marker and no second statement request. Change "format":"pdf" to "csv" and reuse the key: 422 (key reused with a different request).
Part 3: read the design decisions (free)
Authentication (Auth/CognitoAuthentication.cs)
Cognito access tokens have no aud claim, so audience validation is off and the API checks three things instead: the issuer, token_use == "access", and client_id against an allow list of app clients. The signature algorithm is pinned to RS256 so an attacker cannot ask for none or an HMAC variant. MapInboundClaims = false keeps claim names as issued (sub, scope, client_id) rather than renaming them to long Microsoft schema names. The same AccessTokenChecks run in local test mode, so tests exercise the production rules.
Authorisation (Auth/AuthenticationSetup.cs, Accounts/AccountStores.cs)
Policies accounts:read and statements:write require an authenticated user, a customer_id claim and the matching scope. CustomerClaimsTransformation adds customer_id by looking up sub in ICustomerDirectory. A user with no record gets no claim and therefore a 403. Handlers read customer_id from the principal only, never from the URL, query string or body. The store methods take customerId as a parameter, so an unfiltered query is impossible to write by accident.
Validation (Accounts/RequestValidation.cs)
Shape errors (malformed JSON, wrong type, missing field) are 400. Business rule errors (reversed dates, a range over 12 months, a future end date) are 422. In AWS, API Gateway repeats the shape check with a JSON Schema model before the Lambda is invoked; the app repeats it anyway, because the app must be safe when reached directly.
Idempotency (Idempotency/)
The filter requires an Idempotency-Key, scopes it by customer (customerId#key), fingerprints the request, and asks the store to begin. DynamoDbIdempotencyStore uses a conditional PutItem to claim the key atomically. Outcomes: started (run the endpoint and store the response), replay (return the stored response), mismatch (422) and in progress (409 with Retry-After). An abandoned lock can be reclaimed after a timeout, and DynamoDB TTL deletes completed records later. See Idempotency keys for the full reasoning.
Observability (Hosting/)
CorrelationIdMiddleware accepts a well-formed caller X-Correlation-ID (8 to 64 letters, digits and hyphens, so it cannot inject log text), falls back to the root of X-Amzn-Trace-Id, and otherwise generates a UUID v7. It echoes the id and puts it in a logging scope, so every JSON log line of the request carries it. GlobalExceptionHandler turns exceptions into RFC 9457 ProblemDetails without stack traces.
Throttling (Hosting/RateLimiting.cs, CDK stage settings)
API Gateway stage throttling is set to a steady rate of 20 requests per second with a burst of 40 across the stage. The app has a fixed-window limiter partitioned by customer_id (120 per minute by default) returning 429 with Retry-After. WAF adds a per-IP rate-based rule (100 requests per 60 seconds in this lab). Three layers, three different keys.
Resilience (Accounts/CoreBankingAccountStore.cs)
The optional Accounts:Source=CoreBanking mode reads from a simulated core banking system through a typed HttpClient with the standard resilience pipeline: total timeout, retries with exponential back-off and jitter (GET only), a circuit breaker and a per-attempt timeout. A 404 from the core means "not visible to this customer". This is the Lab 4.4 pattern from Calling partner APIs.
Part 4: deploy for under an hour (credits)
Cost and scope
Deploying creates a Cognito user pool, a REST API, a Lambda function, a DynamoDB table and log groups. Lab traffic costs cents. The WAF stack in Part 5 costs about 0.011 USD per hour while it exists, so deploy it, test and destroy it the same day. Use only the sandbox account.
Sign in and publish the API for Lambda
aws sso login --profile learn-sandbox
aws sts get-caller-identity --profile learn-sandbox
# Publish for the Lambda arm64 runtime.
dotnet publish src/Harbourline.AccountInformation.Api -c Release -r linux-arm64 --self-contained false -o artifacts/apiDeploy identity, data, Lambda and the REST API
cd infra/cdk
# Pick a globally unique Cognito domain prefix.
cdk deploy HlM04-AccountInformation --profile learn-sandbox -c domainPrefix=hl-m04-accounts-<yourname> -c owner=<yourname>Keep the outputs: ApiUrl, UserPoolId, WebClientId and HostedDomain.
Create two test users and map them
In the Console: Cognito → User pools → hl-m04-customers → Users → Create user. Use addresses like alice@example.com and bob@example.com and strong passwords. Read each user's sub from the user's details, then redeploy with the mapping:
cdk deploy HlM04-AccountInformation --profile learn-sandbox -c domainPrefix=hl-m04-accounts-<yourname> \
-c customerMapJson='{"<alice-sub>":"CUS-00012345","<bob-sub>":"CUS-00067890"}'Without the mapping, a valid token for a user not in the map gets a 403 from the app. That is the behaviour you want from the second layer.
Get tokens and call the API
Use the hosted login with authorization code plus PKCE using the WebClientId and HostedDomain outputs, for example with Postman's OAuth 2.0 helper (callback http://localhost:5173/callback, scopes openid, harbourline-accounts/accounts.read, harbourline-accounts/statements.write). Call ApiUrl with the access token. Repeat the Part 2 attacks as Alice and as Bob.
Part 5: add and attack AWS WAF (Lab 4.7, credits)
Deploy the web ACL
cdk deploy HlM04-Waf --profile learn-sandbox -c domainPrefix=hl-m04-accounts-<yourname>The stack creates a regional web ACL with two AWS managed rule groups (AWSManagedRulesCommonRuleSet, AWSManagedRulesKnownBadInputsRuleSet) and a rate-based rule that blocks with a 429 after 100 requests per IP in a 60 second window, then associates it with the API stage.
Attack your own API from one IP
API=https://<api-id>.execute-api.us-east-1.amazonaws.com/learn
for i in $(seq 1 300); do curl -s -o /dev/null -w "%{http_code}\n" "$API/v1/accounts"; done | sort | uniq -cExpect mostly 401 (no token) at first, then 429 once WAF's detection kicks in, which can take a minute or two. Only attack APIs you own. Load-testing third-party endpoints can breach their terms and the law.
Destroy the web ACL now
cdk destroy HlM04-Waf --profile learn-sandboxAWS Console instructions
- Cognito: Console → Amazon Cognito → User pools →
hl-m04-customers. Check App integration → Resource servers (the scopes), App clients (hl-m04-web, public client, PKCE) and Users. - API Gateway: Console → API Gateway →
hl-m04-account-information→ Resources. Open each method's Method request and confirm the authorisation scopes. Stages → learn → Logs and tracing shows access logs. - WAF: Console → AWS WAF → Web ACLs → us-east-1 →
hl-m04-account-information→ Sampled requests, to see what was blocked. - DynamoDB: Console → Tables →
hl-m04-idempotency→ Explore items, to see a stored key (customer and key, never the secret body).
Menu wording changes over time (⚠ VERIFY).
AWS CLI
# Find the stack outputs
aws cloudformation describe-stacks --stack-name HlM04-AccountInformation \
--query "Stacks[0].Outputs" --profile learn-sandbox --region us-east-1
# Tail the Lambda's structured logs, filtered by one correlation id
aws logs tail /aws/lambda/hl-m04-account-information --since 15m --format short \
--filter-pattern '"<correlation-id>"' --profile learn-sandbox --region us-east-1
# Idempotency records (expect scoped keys such as CUS-00012345#<uuid>)
aws dynamodb scan --table-name hl-m04-idempotency --max-items 5 --profile learn-sandbox --region us-east-1The scan is for a small lab table only. Never scan a production table.
Infrastructure as Code
The project ships CDK in C#. A Terraform version is not included; the equivalent resources are aws_cognito_user_pool, aws_cognito_resource_server, aws_api_gateway_rest_api with a COGNITO_USER_POOLS authorizer, aws_lambda_function, aws_dynamodb_table with TTL and aws_wafv2_web_acl with aws_wafv2_web_acl_association.
var readScope = new ResourceServerScope(new ResourceServerScopeProps
{
ScopeName = "accounts.read", ScopeDescription = "Read your own accounts and transactions",
});
var resourceServer = pool.AddResourceServer("ResourceServer", new UserPoolResourceServerOptions
{
Identifier = "harbourline-accounts",
Scopes = [readScope /* , writeScope */],
});
MethodOptions Scoped(string scopeName) => new()
{
Authorizer = authorizer,
AuthorizationType = AuthorizationType.COGNITO,
AuthorizationScopes = [$"harbourline-accounts/{scopeName}"], // API Gateway checks the access token's scope
};
accounts.AddMethod("GET", integration, Scoped("accounts.read"));// Four item-level actions on one table: no Scan, no table administration.
function.AddToRolePolicy(new PolicyStatement(new PolicyStatementProps
{
Actions = ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem"],
Resources = [table.TableArn],
}));Complete code
The complete project is in labs/m04-account-information-api/. The core of the authorisation design, the endpoint registration:
var v1 = app.MapGroup("/v1")
.RequireRateLimiting(RateLimiting.PerCustomerPolicy)
.RequireCors(CorsSetup.PolicyName);
v1.MapGet("/accounts", ListAccounts).RequireAuthorization(Policies.AccountsRead);
v1.MapGet("/accounts/{accountId}", GetAccount).RequireAuthorization(Policies.AccountsRead);
v1.MapGet("/accounts/{accountId}/transactions", ListTransactions).RequireAuthorization(Policies.AccountsRead);
v1.MapPost("/accounts/{accountId}/statement-requests", CreateStatementRequest)
.RequireAuthorization(Policies.StatementsWrite)
.AddEndpointFilter<IdempotencyFilter>();
v1.MapGet("/statement-requests/{statementRequestId}", GetStatementRequest).RequireAuthorization(Policies.AccountsRead);
// The customer always comes from the validated token, never from the URL, query or body.
private static string CustomerId(ClaimsPrincipal user) =>
user.FindFirst(CustomerClaimsTransformation.CustomerIdClaim)?.Value
?? throw new InvalidOperationException("Authorisation policy guarantees a customer_id claim.");internal static async Task<IResult> GetAccount(string accountId, ClaimsPrincipal user, IAccountStore store, CancellationToken ct)
{
if (!RequestValidation.AccountIdPattern().IsMatch(accountId))
{
return NotFound(); // a malformed id cannot belong to anyone
}
var account = await store.GetAccountAsync(CustomerId(user), accountId, ct);
return account is null ? NotFound() : Results.Ok(AccountResponse.From(account));
}public static string? Check(ClaimsPrincipal? principal, IReadOnlyCollection<string> allowedClientIds)
{
var tokenUse = principal?.FindFirst("token_use")?.Value;
var clientId = principal?.FindFirst("client_id")?.Value;
if (!string.Equals(tokenUse, "access", StringComparison.Ordinal))
return "Only access tokens are accepted (an ID token is for the client, not for APIs).";
if (clientId is null || !allowedClientIds.Contains(clientId, StringComparer.Ordinal))
return "This app client may not call the API.";
return null;
}Code explained line by line
MapGroup("/v1")withRequireRateLimitingandRequireCorsapplies the per-customer limiter and CORS policy to all five endpoints in one place, so a new endpoint cannot forget them.- Each endpoint names its policy with
RequireAuthorization.accounts:readandstatements:writeare separate scopes, so a read-only token cannot create anything. AddEndpointFilter<IdempotencyFilter>()wraps only the one write endpoint. Reads are naturally idempotent and need no key.CustomerId(user)throws if the claim is missing. The authorisation policy already guarantees it, so reaching the exception means a wiring mistake, which should be loud.- The regular expression check returns the same 404 as a missing account. Returning 400 for malformed ids and 404 for unknown ones would let an attacker learn which ids have a valid shape.
store.GetAccountAsync(CustomerId(user), accountId, ct)passes the customer into the query. The "not yours" case is a query that returns nothing, not a separate check afterwards.Checkruns insideOnTokenValidated, after the signature and lifetime are already verified.token_usestops an ID token being used as an API credential;client_idstops a token minted for some other app client in the same pool.ValidateAudience = falseis deliberate because Cognito access tokens carryclient_idinstead ofaud. It is paired with the explicit client allow list. Switching audience validation on without understanding this causes every token to fail.- In
Program.cs,app.UseCors()comes beforeUseAuthentication()andUseRateLimiter()comes after it;UseAuthorization()follows the limiter. Reordering these changes behaviour (preflight failures, or a limiter that can only key on IP).
Security considerations
⚠ Learning shortcut — not for production
The customer directory is a map from configuration (CustomerDirectory__MapJson), the user pool and DynamoDB table use RemovalPolicy.DESTROY, MFA is optional, the Lambda function runs without a VPC and with X-Ray on, /dev/tokens exists in Development, and CORS allows a single placeholder origin. In production: a customer table written at onboarding and keyed by sub, RETAIN and deletion protection on the pool and table, required MFA with step-up, threat protection, a VPC or PrivateLink path to the core banking system, a real front-end origin list, and AWS WAF attached from day one.
- BOLA is the main risk (OWASP API1). The second-user tests exist because it is the easiest bug to ship.
- Access tokens only. An ID token is a statement to the client about the user; an API that accepts it can be called with tokens never meant for it.
- Local token issuer.
Auth:Mode=LocalTestIssueris refused outside Development by an explicitInvalidOperationException. Keep that guard; it is a control. - No stack traces, no internal ids. Errors are ProblemDetails; account responses omit the customer id.
- Logs. Log the correlation id, customer id and outcome. Do not log tokens, full account numbers or request bodies. UK GDPR treats identifiers as personal data, so retention and access to these logs need a decision (⚠ legal review required; this project does not make a system compliant with anything).
- Money as decimal strings. Never
doublefor amounts. - Least privilege. The Lambda role has four DynamoDB item actions on one table and the managed basic execution policy.
Banking use case
A retail bank's mobile app shows balances and recent transactions, and lets the customer request a statement as a PDF or CSV. The first call after login is GET /v1/accounts; the customer never types an account id into the URL themselves. The statement request is the only write, and mobile networks retry, so it carries an idempotency key. The gateway protects the front door (token, scope, schema, throttle), WAF absorbs scripted abuse, and the app enforces what only it can: which customer owns which account. Support staff investigate a complaint by pasting the correlation id from the customer's error message into the log search.
Common mistakes
- Trusting a
customerIdin the path, query or body. The identity is the token, not anything the client writes. - Returning 403 for "not yours". That confirms the resource exists. Return 404.
- Accepting ID tokens because they "validate fine".
- Turning on audience validation for Cognito access tokens and then wondering why every request is a 401.
- Putting the rate limiter before authentication, which can then only key by IP.
- Trusting API Gateway alone. If the Lambda can be reached by another path, it needs its own checks. Keep the app's validation even when the gateway also validates.
- Leaving the WAF stack deployed. It bills hourly; destroy it the same day.
- Using the Development token endpoint outside Development.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| 401 from API Gateway with a valid-looking token | An ID token was sent instead of an access token | Send the access token |
| 403 from API Gateway | The token lacks the scope required by that method | Request the scope in the authorize call |
| 403 from the app (ProblemDetails) | The user's sub is not in customerMapJson | Redeploy with the mapping |
| 502 from API Gateway | Lambda failed to start: missing publish output or wrong architecture | Republish for linux-arm64; read /aws/lambda/hl-m04-account-information |
cdk deploy fails on the domain | Cognito domain prefix already taken | Choose another domainPrefix |
cdk synth reports cdk-nag errors | A rule fired that is not acknowledged, or an ID lacks its bracketed suffix | Read the finding, fix it or acknowledge it with a reason using the exact ID |
dotnet test is green but dotnet build infra/cdk/... fails | Test runs do not necessarily build the CDK project | Build the CDK project explicitly (it compiles after the cdk-nag v3 fixes above) |
| 429 immediately in tests | The per-customer limiter window is tiny in the test configuration | Intended: the test proves the limiter |
| No log lines for a correlation id | Logs not yet delivered, or filtering the wrong group | Wait a minute; use /aws/lambda/hl-m04-account-information |
Cost and cleanup
Local part: free. Deployed part: credits (cents per hour; WAF about 0.011 USD per hour plus request charges while it exists; Cognito Essentials is free up to a monthly-active-user allowance, ⚠ VERIFY the current tier and prices).
cd infra/cdk
cdk destroy HlM04-Waf HlM04-AccountInformation --profile learn-sandbox
# Nothing tagged for the lab should remain (the tagging API can lag a few minutes):
aws resourcegroupstaggingapi get-resources \
--tag-filters Key=Project,Values=cea-lab Key=Lab,Values=m04-account-information-api \
--query "ResourceTagMappingList[].ResourceARN" --profile learn-sandbox --region us-east-1
# Local build output
find labs/m04-account-information-api -type d \( -name bin -o -name obj -o -name TestResults -o -name cdk.out \) -prune -exec rm -rf {} +The stacks use RemovalPolicy.DESTROY for the user pool, table and log groups so that teardown is complete. That is a learning shortcut; production retains them.
Exercises
- 🟢 Guided: run the tests, start the API, and perform the four attacks as Alice. Fill in a table of request, status, and the reason the API gave.
- 🟡 Challenge: add a new read operation,
GET /v1/accounts/{accountId}/balance, with theaccounts.readscope. Add it to the OpenAPI design file first, then to the handlers, then to the CDK resource tree. Write an ownership test with the second user before you write the handler. - 🔴 Live problem: a partner reports that "some statement requests are created twice, but only when their mobile network is bad". Logs show two different
Idempotency-Keyvalues 4 seconds apart. Decide whether the API, the client or both are at fault, what you would ask the client team to change, and what server-side evidence you can add (a log field, a metric) to prove duplicates are client-generated keys rather than a store failure.
Assignment
Produce the project deliverable for your portfolio repository: (1) a README with the architecture diagram and the table of requirements to tests, (2) the OpenAPI design file updated for your new endpoint, (3) the output of the four attacks, (4) a short threat model listing five threats against this API with the control and the test for each, and (5) a one-page note on what must change before this could handle real customer data. This is the seed of Capstone 1.
Solutions
| Request | Status | Why |
|---|---|---|
GET /v1/accounts/ACC-0000067890 as Alice | 404 | Bob's account is outside Alice's list; same answer as a missing account |
GET /v1/accounts/not-an-account | 404 | The id fails the shape check; it cannot belong to anyone |
GET /v1/accounts without a token | 401 | No credential; the response carries a bearer challenge |
GET .../transactions?pageSize=500 | 400 | Shape error: pageSize must be 1 to 100 |
| POST with a reversed date range | 422 | Well-formed, but breaks a business rule |
In account-information.design.yaml, add the path with operationId: getBalance, the accounts.read security requirement, AccountId parameter and the same 401, 403, 404, 429 responses. Add IAccountStore.GetBalanceAsync(customerId, accountId, ct) returning null when the account is not the customer's. The handler returns NotFound() for a null result and for a malformed id. In the CDK stack: account.AddResource("balance").AddMethod("GET", integration, Scoped("accounts.read")). The test comes first: Alice requests Bob's balance and expects 404, and Alice requests her own and expects 200 with a decimal string. Because the new route sits under the /v1 group, the limiter, CORS and the scope policy come for free.
Two different keys four seconds apart mean the client generated a new key for the retry, so the server did the right thing: it cannot know the two requests are the same. The fix is on the client: generate the key once per user action (when the user taps "request statement"), store it with the pending action, and reuse it for every retry. Server-side evidence: log the idempotency key hash, the customer id and the outcome (started, replayed, mismatch) on every write, and expose a metric for replayed. A healthy client shows replays; this client shows none. Also check the other direction: if the store were failing you would see started outcomes with identical keys, or 5xx from DynamoDB, neither of which the logs show.
Knowledge check
Answer: 403 confirms that the account exists. An attacker could walk the id space and learn which accounts exist. 404 for both "missing" and "not yours" removes that signal (OWASP API1, broken object-level authorisation).
Answer: The API returns 401, because token_use is not access. ID tokens are for the client application. If APIs accepted them, any token issued for sign-in could be replayed as an API credential.
Answer: 400 means the request is malformed (cannot be parsed or fails the schema). 422 means it is well-formed but breaks a business rule, for example an end date before the start date.
Answer: API Gateway limits per stage and method and protects the backend as a whole. WAF's rate-based rule keys by IP and stops one source flooding the edge. The app's limiter keys by customer, which only the app can identify, so one noisy customer cannot consume everyone's capacity.
Answer: The server returns 422. Replaying the old response would hide that the client changed its mind; running the new body would break the promise that a key identifies one request.
Interview questions
- "How do you make sure customer A cannot read customer B's accounts?" The customer comes from the validated token mapped on the server, every query is parameterised by that customer, "not yours" returns 404, and a second-user test fails the build if it regresses.
- "Why not accept the customer id in the URL?" Anything the client sends can be changed. The token is the only trusted statement about identity.
- "What does the gateway do that the app must also do?" Authenticate, check scopes and validate shapes. The gateway fails fast and cheaply, but the app must not assume the gateway is the only path to it.
- "How would you roll this out?" Deploy behind WAF, start in count mode for managed rules, add alarms on 4xx, 5xx, throttles and idempotency mismatches, and rehearse the runbook for a leaked token.
Certification practice
A REST API behind a Cognito authoriser must allow read-only tokens to call GET methods but forbid them from calling POST /statement-requests. Which design is the SIMPLEST and correct?
A. Create two user pools.
B. Define resource-server scopes (for example accounts.read and statements.write), set AuthorizationScopes on each method, and request only the needed scopes in the token.
C. Check the user's email domain in the Lambda function.
D. Put the POST method on a different stage.
Answer: B. The Cognito authoriser compares the access token's scopes with the method's required scopes. A is excessive. C is not authorisation. D does not change who can call it.
A public API is being scraped by a few IP addresses that make thousands of requests per minute, and a separate customer is exhausting a shared backend with legitimate traffic. Which combination BEST addresses both?
A. An AWS WAF rate-based rule keyed by IP, plus an application-level limit keyed by authenticated customer. B. Only larger Lambda memory. C. Only a bigger DynamoDB table. D. Only a CloudFront cache.
Answer: A. WAF contains abusive sources at the edge; the app limits per customer because only it knows who the customer is. B and C do not limit abuse. D helps only for cacheable public content, not authenticated per-customer data.
An API accepts any valid token from its Cognito user pool. A security review shows a token minted for the bank's marketing site can call the account API. What control is missing?
A. A longer token lifetime.
B. An allow list of permitted app client ids (and token_use check) in the API.
C. A larger password policy.
D. Disabling MFA.
Answer: B. Tokens from different app clients in the same pool all validate against the same keys, so the API must check client_id (and that the token is an access token). A, C and D do not restrict which application's tokens are accepted.
Completion checklist
- I ran the tests and saw
total: 55, succeeded: 54, skipped: 1 - I attacked the API as Alice and understood every status code
- I can explain why "not yours" is a 404 and where the customer id comes from
- I read the CDK stack and the cdk-nag v3 notes
- If I deployed: I destroyed the WAF stack, then the API stack, and the tag query returned nothing
- I wrote the portfolio README and threat model
Key takeaways
- Identity is the token; the customer is resolved on the server and passed into every query.
- Authorise operations with scopes and objects with ownership. Both are needed.
- Return 404 for missing and not-yours alike; return 400 for malformed input and 422 for business-rule failures.
- Idempotency keys are scoped by customer, fingerprinted and stored with a conditional write plus TTL.
- Throttle at three layers (gateway, WAF, app) because each sees a different identity.
- With cdk-nag v3, register the pack as a validation plugin and acknowledge findings with exact IDs and honest reasons.
Further reading
- REST API design and OpenAPI and contract testing, for the design side
- OAuth 2.0, OIDC and JWTs and Cognito user pools, for the identity side
- Idempotency keys, API security with WAF and the OWASP API Top 10 and API monitoring
- Module 4 overview
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.
Integrating with core banking and mainframes: hybrid networks, private APIs and MQ messaging
Connect cloud services to an on-premises core banking system safely: choose between Site-to-Site VPN and Direct Connect, expose and consume private APIs, use request/reply messaging with Amazon MQ (or RabbitMQ locally), and translate COBOL copybook records with EBCDIC and packed decimals into a clean C# domain model behind an anti-corruption layer.
Module 4 cheat sheet
One-page revision summary for API Development & Integration: services, Azure mapping, CLI commands, limits, decision rules, exam traps and cost traps.