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

API security: AWS WAF and the OWASP API Security Top 10 for a banking API

Map every OWASP API Security Top 10 (2023) risk to a concrete control on AWS or in .NET, attach a WAF web ACL with managed and rate-based rules to an API Gateway REST API, and enforce object- and property-level authorisation in ASP.NET Core so a customer can only ever see their own accounts.

intermediate⏱ 2 h 30 min🟡 Low costSCS-C03DVA-C03SAA-C03

Assumes: .NET 10 LTS · ASP.NET Core 10 · AWS SDK for .NET v4 · AWS WAF (wafv2) · CDK v2 (Amazon.CDK.Lib 2.277.0) · Terraform AWS provider v6 · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Name the ten risks in the OWASP API Security Top 10 (2023) and explain each one with a banking example.
  • Decide, for each risk, whether the control belongs in AWS WAF, API Gateway, Cognito/authorizers or your .NET code, and explain why WAF alone cannot stop the top risk.
  • Attach a web ACL to an API Gateway REST API stage with AWS managed rule groups and a rate-based rule keyed on caller and route, roll it out in Count mode and read the results.
  • Implement object-level (BOLA) and property-level (BOPLA) authorisation in ASP.NET Core, with tests that prove customer A cannot read customer B's account.
  • Build a short API security checklist for design reviews.

Prerequisites

Why this matters in banking

Harbourline Bank's (fictional) Account Information API returns GET /accounts/{accountId}. In a penetration test, a tester signs in as customer CUS-00012345, receives a perfectly valid token, and changes the URL from ACC-0000123456 (theirs) to ACC-0000123457. The API returns someone else's balance and IBAN.

Nothing was "hacked" in the traditional sense. The token was real, the request was well formed, WAF saw nothing suspicious, API Gateway validated the JWT, and the backend simply forgot to check whose account it was. This is Broken Object Level Authorization, number one in the OWASP API Security Top 10, and it is the most common serious API bug in financial services. Under UK GDPR it is a personal data breach that may need reporting to the regulator, and to the customers affected.

The lesson's core message: edge controls reduce noise and abuse; only your code can enforce who may see what.

The idea in plain language

The OWASP API Security Top 10 is a community list of the most damaging ways APIs are attacked. It differs from the classic OWASP Top 10 for web apps: most API risks are about authorisation and business logic, not injection strings.

AWS WAF (web application firewall) inspects each HTTP request before it reaches API Gateway and can allow, block, count, or challenge it based on rules: known-bad patterns, IP reputation, geography, size limits and request rates. It sees the request, not your data model: it cannot know that ACC-0000123457 belongs to someone else.

Analogy: WAF is the security guard at the bank's front door: they stop people carrying crowbars, people on a watch list and the person who has tried the door 500 times in a minute. The guard cannot tell whether a smartly dressed customer is about to open a safe-deposit box that belongs to someone else. That check happens at the box itself, by comparing the key holder with the box's owner: your authorisation code.

So defence in depth for an API is a stack:

  1. WAF — drop obvious attacks and volumetric abuse cheaply.
  2. API Gateway — authenticate (JWT/Cognito/authorizer), throttle, validate request shape.
  3. Your service — authorise every object and every property, enforce business limits.
  4. Monitoring — notice what got through.

What problem the AWS services solve

LayerAWS featureGood atHonest limitations
Edge filteringAWS WAF web ACL on an API Gateway REST API stage (also ALB, CloudFront, Cognito user pools, AppSync and others)Managed rule groups for common exploits and bad inputs, IP reputation, rate-based rules, size limits, geo rules, custom responsesNo WAF on HTTP APIs (front them with CloudFront plus WAF if you must). WAF inspects only the first part of large bodies (16 KB by default for API Gateway, configurable at extra cost). Cannot evaluate object ownership
IdentityCognito user pools, JWT and Lambda authorizers, IAM/SigV4, mTLSProving who the caller is and which scopes they holdScopes say "may read accounts", not "may read this account"
Shape and volumeAPI Gateway request validation, throttling, usage plansRejecting malformed input and bursts before your code runsUsage plans and API keys are not authentication; validation does not check meaning
Business authorisationYour ASP.NET Core code (resource-based authorisation, DTOs)Ownership checks, property filtering, business limitsOnly as good as your tests
DetectionAccess logs, WAF logs, CloudWatch metrics, GuardDutySeeing enumeration, spikes and anomaliesDetection after the fact; needs alarms that someone acts on

WAF pricing (standard tier, us-east-1, verified 2026-11-18): USD 5 per web ACL per month, USD 1 per rule or managed rule group per month, USD 0.60 per million requests, with extra request charges above 1,500 WCUs or for larger body inspection. Some managed rule groups (Bot Control, Account Takeover Prevention, Account Creation Fraud Prevention) carry their own subscription and request fees.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Azure Front Door / Application Gateway WAF policyAWS WAF web ACLRules are priced individually; capacity measured in WCUs
OWASP Core Rule Set (CRS) managed rulesAWSManagedRulesCommonRuleSet, KnownBadInputsRuleSet, SQLiRuleSet and othersAWS-authored rule groups, not CRS; tune with rule action overrides
Front Door rate-limit rulesRate-based rules with custom aggregation keysKeys can combine IP, header, query argument, URI path, HTTP method and labels
APIM validate-jwt + check-header policiesJWT/Cognito authorizer + Lambda authorizerOwnership checks still belong in code
ASP.NET Core IAuthorizationService resource-based authExactly the sameYour existing .NET skills are the main BOLA defence
Microsoft Defender for APIsGuardDuty, Security Hub, WAF logs + CloudWatchNo single "API posture" product; you combine services

The OWASP API Security Top 10 (2023) mapped to controls

#RiskBanking examplePrimary controlWhere
API1Broken Object Level Authorization (BOLA)Change accountId in the URL and see another customer's balanceCheck that the token's subject owns the object, on every request; unguessable IDs as a secondary measure.NET code
API2Broken AuthenticationLogin endpoint allows unlimited password guesses; tokens accepted without audience checkCognito with MFA, strict JWT validation (issuer, audience, expiry, token_use), rate-limit loginCognito, authorizer, WAF rate rule
API3Broken Object Property Level Authorization (BOPLA)Response includes riskRating and kycStatus; PATCH lets customer set status=open on a frozen accountExplicit response DTOs; explicit input DTOs (no mass assignment).NET code
API4Unrestricted Resource ConsumptionGET /transactions?pageSize=1000000; statement PDF generation without limitsMax page size, request validation, throttling, timeouts, WAF rate rules, Lambda concurrency limitsAPI Gateway, code, WAF
API5Broken Function Level AuthorizationA customer token can call POST /admin/accounts/{id}/freezeSeparate admin API, scopes per route, deny by defaultAuthorizer, API Gateway, code
API6Unrestricted Access to Sensitive Business FlowsBots open thousands of accounts to harvest sign-up bonuses; card testing on a payment endpointBusiness limits (per customer, per device), step-up auth, Bot Control / ACFP managed rules, CAPTCHA/challengeCode, WAF
API7Server-Side Request Forgery (SSRF)Customer-supplied webhook URL points at the instance metadata endpointAllowlist destinations, block private ranges, IMDSv2, egress controlCode, network (see Webhooks)
API8Security MisconfigurationVerbose stack traces, permissive CORS * with credentials, TLS 1.0 allowedProblemDetails without internals, strict CORS, TLS security policy, IaC reviewsAPI Gateway, code, IaC
API9Improper Inventory ManagementForgotten v1 stage without the new authorizer still reachableAPI inventory, OpenAPI as source of truth, retire old stages, tag everythingGovernance, API Gateway
API10Unsafe Consumption of APIsTrusting a partner API's response and writing its HTML into a statementValidate partner responses, timeouts, TLS, schema checks (see Calling partner APIs)Code

Notice that WAF is a primary control for only parts of API2, API4 and API6. Everything else is identity, configuration or code.

Architecture

Security-boundary view.

  • Internet zone: everything before WAF is untrusted.
  • Edge zone (AWS managed): WAF and API Gateway. Configuration here is code-reviewed IaC; changes are logged in CloudTrail.
  • Application zone (private subnets): the service trusts the authenticated identity passed by API Gateway (validated JWT claims) but not any identifier in the path, query or body. Every object lookup is scoped by the caller's customer ID.
  • Data zone: the store itself can enforce scoping (for example, a DynamoDB partition key of customerId, so a query physically cannot return another customer's items).

Step-by-step implementation

Start with an inventory and a threat list (API9)

List every route, stage and version in the OpenAPI document from OpenAPI contracts. For each route, write who may call it (customer, staff, partner), which scope it needs, and which object it touches. Routes nobody can explain are candidates for deletion. Old stages are the classic "forgotten door".

Authenticate strictly at the gateway (API2, API5)

Use the Cognito/JWT authorizer to check issuer, audience/client ID, expiry and scope per route. Put staff-only operations in a separate API with a separate user pool or IAM auth, rather than mixing admin routes into the customer API. Deny by default: a route without an authorizer should fail your IaC checks.

Constrain shape and volume (API4)

  • API Gateway request validators with models: pageSize is an integer from 1 to 100; accountId matches ^ACC-[0-9]{10}$.
  • Stage and method throttling (burst and rate), plus usage plans for partners.
  • In code, clamp pageSize again (defence in depth) and set timeouts on every downstream call.

Attach a WAF web ACL in Count mode

Create a Regional web ACL with:

  1. AWSManagedRulesAmazonIpReputationList — known malicious sources.
  2. AWSManagedRulesCommonRuleSet — common exploit patterns. Watch SizeRestrictions_BODY, which blocks bodies over 8 KB; override it to Count if your API legitimately accepts larger payloads, and enforce your own size limit instead ⚠ VERIFY the current size threshold in the rule group documentation.
  3. AWSManagedRulesKnownBadInputsRuleSet — exploit payloads such as Log4j-style lookups.
  4. A rate-based rule "per IP per route": aggregate on IP plus URI path, limit 300 requests per 5 minutes, scoped to /accounts, returning a custom 429 JSON body.
  5. A stricter rate rule on authentication-related routes, if they pass through this ACL.

Set every rule to Count first. Rate-based rules accept a limit as low as 10 and an evaluation window of 60, 120, 300 or 600 seconds.

Read the results, then switch to Block

After a day (or a load test in the lab), query WAF logs or sampled requests: which rules matched, on which routes, from which clients. Fix false positives with scope-down statements or rule action overrides, then switch rules to Block. Record the decision in the change log.

Enforce ownership and properties in code (API1, API3)

Use ASP.NET Core resource-based authorisation: load the account, then ask an IAuthorizationService whether the current user may read it. Return 404 rather than 403 for objects the caller does not own, so attackers cannot enumerate which IDs exist. Map entities to response DTOs that contain only the fields the customer may see, and bind updates to input DTOs that contain only fields the customer may change.

Protect sensitive business flows (API6)

Put business limits in the domain: maximum new payees per day, maximum payment value without step-up authentication, cool-down after adding a payee. Consider WAF Bot Control or ACFP on sign-up and login flows (paid managed rule groups) and the Challenge/CAPTCHA actions for browser clients.

Prove it with tests

Write integration tests that sign in as two different customers and attempt every cross-customer access. These tests are the evidence that API1 is mitigated; they should fail the build if anyone removes the ownership check.

AWS Console instructions

  • Create the web ACL: Console → AWS WAF & Shield → Web ACLs (in the newer console experience, web ACLs may appear as protection packs) → Create → Resource type Regional resources, Region US East (N. Virginia) → name hl-m04-accounts-acl → Add AWS resources → choose the API Gateway REST API stage.
  • Add managed rules: Add rules → Add managed rule groups → AWS managed rule groups → enable Amazon IP reputation list, Core rule set, Known bad inputs. For each, choose Override all rule actions to Count for the first rollout.
  • Add the rate rule: Add rules → Add my own rules → Rate-based rule → rate limit 300, evaluation window 5 minutes → Custom keys → add IP address and URI path → Scope-down statement: URI path starts with /accounts → Action Count (later Block with custom response code 429).
  • Logging: web ACL → Logging and metrics → Enable → destination a CloudWatch Logs log group whose name starts with aws-waf-logs- → add redacted fields: the authorization header.
  • Check results: web ACL → Overview and Sampled requests, or run a Logs Insights query on the WAF log group.

AWS CLI

PROFILE=learn-sandbox
REGION=us-east-1

# 1. Create the web ACL from a JSON rules file (rules.json shown below), default action Allow
aws wafv2 create-web-acl --name hl-m04-accounts-acl --scope REGIONAL \
  --default-action Allow={} \
  --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName=hl-m04-accounts-acl \
  --rules file://rules.json \
  --tags Key=Project,Value=cea-lab Key=Lab,Value=m04-l18 Key=Environment,Value=learn Key=Owner,Value=you \
  --profile $PROFILE --region $REGION

# 2. Associate it with the REST API stage (ARN format for API Gateway stages)
aws wafv2 associate-web-acl \
  --web-acl-arn arn:aws:wafv2:us-east-1:111122223333:regional/webacl/hl-m04-accounts-acl/EXAMPLE-ID \
  --resource-arn arn:aws:apigateway:us-east-1::/restapis/a1b2c3d4e5/stages/prod \
  --profile $PROFILE --region $REGION

# 3. Send WAF logs to CloudWatch Logs (log group name must start with aws-waf-logs-), redacting the Authorization header
aws logs create-log-group --log-group-name aws-waf-logs-hl-m04 --profile $PROFILE --region $REGION
aws logs put-retention-policy --log-group-name aws-waf-logs-hl-m04 --retention-in-days 30 --profile $PROFILE --region $REGION
aws wafv2 put-logging-configuration --logging-configuration '{
  "ResourceArn": "arn:aws:wafv2:us-east-1:111122223333:regional/webacl/hl-m04-accounts-acl/EXAMPLE-ID",
  "LogDestinationConfigs": ["arn:aws:logs:us-east-1:111122223333:log-group:aws-waf-logs-hl-m04"],
  "RedactedFields": [{"SingleHeader": {"Name": "authorization"}}]
}' --profile $PROFILE --region $REGION

# 4. See which IP/route combinations the rate rule is currently tracking
aws wafv2 get-rate-based-statement-managed-keys --scope REGIONAL \
  --web-acl-name hl-m04-accounts-acl --web-acl-id EXAMPLE-ID --rule-name rate-per-ip-per-route \
  --profile $PROFILE --region $REGION
rules.json
[
  {
    "Name": "aws-ip-reputation",
    "Priority": 0,
    "Statement": { "ManagedRuleGroupStatement": { "VendorName": "AWS", "Name": "AWSManagedRulesAmazonIpReputationList" } },
    "OverrideAction": { "Count": {} },
    "VisibilityConfig": { "SampledRequestsEnabled": true, "CloudWatchMetricsEnabled": true, "MetricName": "ip-reputation" }
  },
  {
    "Name": "aws-common",
    "Priority": 1,
    "Statement": { "ManagedRuleGroupStatement": { "VendorName": "AWS", "Name": "AWSManagedRulesCommonRuleSet" } },
    "OverrideAction": { "Count": {} },
    "VisibilityConfig": { "SampledRequestsEnabled": true, "CloudWatchMetricsEnabled": true, "MetricName": "common" }
  },
  {
    "Name": "aws-known-bad-inputs",
    "Priority": 2,
    "Statement": { "ManagedRuleGroupStatement": { "VendorName": "AWS", "Name": "AWSManagedRulesKnownBadInputsRuleSet" } },
    "OverrideAction": { "Count": {} },
    "VisibilityConfig": { "SampledRequestsEnabled": true, "CloudWatchMetricsEnabled": true, "MetricName": "known-bad-inputs" }
  },
  {
    "Name": "rate-per-ip-per-route",
    "Priority": 3,
    "Statement": {
      "RateBasedStatement": {
        "Limit": 300,
        "EvaluationWindowSec": 300,
        "AggregateKeyType": "CUSTOM_KEYS",
        "CustomKeys": [
          { "IP": {} },
          { "UriPath": { "TextTransformations": [ { "Priority": 0, "Type": "LOWERCASE" } ] } }
        ],
        "ScopeDownStatement": {
          "ByteMatchStatement": {
            "FieldToMatch": { "UriPath": {} },
            "PositionalConstraint": "STARTS_WITH",
            "SearchString": "/accounts",
            "TextTransformations": [ { "Priority": 0, "Type": "LOWERCASE" } ]
          }
        }
      }
    },
    "Action": { "Count": {} },
    "VisibilityConfig": { "SampledRequestsEnabled": true, "CloudWatchMetricsEnabled": true, "MetricName": "rate-per-ip-per-route" }
  }
]

When you move the rate rule to Block, replace "Action": { "Count": {} } with a block action that returns a custom response, for example {"Block": {"CustomResponse": {"ResponseCode": 429, "CustomResponseBodyKey": "too-many"}}}, and add a CustomResponseBodies entry named too-many to the web ACL with a small JSON ProblemDetails body. The general WAF lesson walks through custom responses in detail.

Managed rule groups use OverrideAction; your own rules use Action. Mixing them up is the most common WAFInvalidParameterException.

Infrastructure as Code

infra/cdk/ApiWafStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.Logs;
using Amazon.CDK.AWS.WAFv2;
using Constructs;

namespace Harbourline.Accounts.Infra;

public sealed class ApiWafStackProps : StackProps
{
    public required string StageArn { get; init; } // arn:aws:apigateway:us-east-1::/restapis/{id}/stages/prod
}

public sealed class ApiWafStack : Stack
{
    public ApiWafStack(Construct scope, string id, ApiWafStackProps props) : base(scope, id, props)
    {
        static CfnWebACL.VisibilityConfigProperty Vis(string name) => new()
        {
            SampledRequestsEnabled = true, CloudWatchMetricsEnabled = true, MetricName = name
        };

        static CfnWebACL.RuleProperty Managed(string name, int priority) => new()
        {
            Name = name,
            Priority = priority,
            Statement = new CfnWebACL.StatementProperty
            {
                ManagedRuleGroupStatement = new CfnWebACL.ManagedRuleGroupStatementProperty { VendorName = "AWS", Name = name }
            },
            OverrideAction = new CfnWebACL.OverrideActionProperty { Count = new Dictionary<string, object>() }, // Count first
            VisibilityConfig = Vis(name)
        };

        var acl = new CfnWebACL(this, "AccountsAcl", new CfnWebACLProps
        {
            Name = "hl-m04-accounts-acl",
            Scope = "REGIONAL",
            DefaultAction = new CfnWebACL.DefaultActionProperty { Allow = new Dictionary<string, object>() },
            VisibilityConfig = Vis("hl-m04-accounts-acl"),
            CustomResponseBodies = new Dictionary<string, object>
            {
                ["too-many"] = new CfnWebACL.CustomResponseBodyProperty
                {
                    ContentType = "APPLICATION_JSON",
                    Content = "{\"type\":\"about:blank\",\"title\":\"Too many requests\",\"status\":429}"
                }
            },
            Rules = new object[]
            {
                Managed("AWSManagedRulesAmazonIpReputationList", 0),
                Managed("AWSManagedRulesCommonRuleSet", 1),
                Managed("AWSManagedRulesKnownBadInputsRuleSet", 2),
                new CfnWebACL.RuleProperty
                {
                    Name = "rate-per-ip-per-route",
                    Priority = 3,
                    Statement = new CfnWebACL.StatementProperty
                    {
                        RateBasedStatement = new CfnWebACL.RateBasedStatementProperty
                        {
                            Limit = 300,
                            EvaluationWindowSec = 300,
                            AggregateKeyType = "CUSTOM_KEYS",
                            CustomKeys = new object[]
                            {
                                new CfnWebACL.RateBasedStatementCustomKeyProperty { Ip = new Dictionary<string, object>() },
                                new CfnWebACL.RateBasedStatementCustomKeyProperty
                                {
                                    UriPath = new CfnWebACL.RateLimitUriPathProperty
                                    {
                                        TextTransformations = new object[] { new CfnWebACL.TextTransformationProperty { Priority = 0, Type = "LOWERCASE" } }
                                    }
                                }
                            }
                        }
                    },
                    Action = new CfnWebACL.RuleActionProperty
                    {
                        Block = new CfnWebACL.BlockActionProperty
                        {
                            CustomResponse = new CfnWebACL.CustomResponseProperty { ResponseCode = 429, CustomResponseBodyKey = "too-many" }
                        }
                    },
                    VisibilityConfig = Vis("rate-per-ip-per-route")
                }
            }
        });

        new CfnWebACLAssociation(this, "StageAssociation", new CfnWebACLAssociationProps
        {
            ResourceArn = props.StageArn,
            WebAclArn = acl.AttrArn
        });

        var wafLogs = new LogGroup(this, "WafLogs", new LogGroupProps
        {
            LogGroupName = "aws-waf-logs-hl-m04",
            Retention = RetentionDays.ONE_MONTH,
            RemovalPolicy = RemovalPolicy.DESTROY
        });

        new CfnLoggingConfiguration(this, "WafLogging", new CfnLoggingConfigurationProps
        {
            ResourceArn = acl.AttrArn,
            LogDestinationConfigs = new[] { wafLogs.LogGroupArn.Replace(":*", "") },
            RedactedFields = new object[]
            {
                new CfnLoggingConfiguration.FieldToMatchProperty
                {
                    SingleHeader = new Dictionary<string, object> { ["Name"] = "authorization" }
                }
            }
        });

        Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
        Amazon.CDK.Tags.Of(this).Add("Lab", "m04-l18");
        Amazon.CDK.Tags.Of(this).Add("Environment", "learn");
        Amazon.CDK.Tags.Of(this).Add("Owner", "you");
    }
}

LogGroupArn is a CDK token at synth time, so the string Replace has no effect on it; if CloudFormation rejects the :* suffix, build the ARN with Arn.Format instead ⚠ VERIFY against your CDK version. The property names for custom keys follow the CloudFormation AWS::WAFv2::WebACL schema; check them against the CDK API reference if the build complains.

Complete code

WAF never sees ownership, so the most important code in this lesson is the .NET authorisation. The example is a self-contained ASP.NET Core 10 minimal API plus integration tests. A test authentication handler stands in for the JWT authorizer, so it runs without AWS.

src/Harbourline.Accounts.Api/Harbourline.Accounts.Api.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>
</Project>
src/Harbourline.Accounts.Api/Program.cs
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

// In AWS: JWT bearer validation (or claims forwarded by the API Gateway authorizer).
// Locally and in tests: a header-based scheme so the ownership logic can be exercised.
builder.Services.AddAuthentication(DevHeaderAuthHandler.SchemeName)
    .AddScheme<AuthenticationSchemeOptions, DevHeaderAuthHandler>(DevHeaderAuthHandler.SchemeName, _ => { });

builder.Services.AddAuthorizationBuilder()
    .AddPolicy("accounts.read", p => p.RequireAuthenticatedUser().RequireClaim("scope", "accounts.read"))
    .AddPolicy("accounts.write", p => p.RequireAuthenticatedUser().RequireClaim("scope", "accounts.write"))
    .SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()); // deny by default (API5)

builder.Services.AddSingleton<IAuthorizationHandler, AccountOwnerHandler>();
builder.Services.AddSingleton<AccountRepository>();
builder.Services.AddProblemDetails();

var app = builder.Build();
app.UseExceptionHandler();      // ProblemDetails, no stack traces (API8)
app.UseAuthentication();
app.UseAuthorization();

// API1 + API3: load, authorise against the resource, return a DTO.
app.MapGet("/accounts/{accountId}", async (string accountId, ClaimsPrincipal user,
        AccountRepository repo, IAuthorizationService authz) =>
{
    if (!AccountId.IsValid(accountId))
        return Results.Problem(statusCode: 400, title: "Invalid account id");

    var account = repo.Find(accountId);
    if (account is null) return Results.NotFound();

    var result = await authz.AuthorizeAsync(user, account, AccountOperations.Read);
    // 404, not 403: do not reveal that someone else's account exists.
    return result.Succeeded ? Results.Ok(AccountView.From(account)) : Results.NotFound();
}).RequireAuthorization("accounts.read");

// API4: bounded list scoped to the caller; the store is never asked for "all accounts".
app.MapGet("/accounts", (ClaimsPrincipal user, AccountRepository repo, int? pageSize) =>
{
    var size = Math.Clamp(pageSize ?? 20, 1, 100);
    var customerId = user.FindFirstValue("sub")!;
    return Results.Ok(new { items = repo.ForCustomer(customerId).Take(size).Select(AccountView.From) });
}).RequireAuthorization("accounts.read");

// API3: only the nickname can be changed by a customer; status, balance, riskRating cannot.
app.MapPatch("/accounts/{accountId}", async (string accountId, AccountUpdate update, ClaimsPrincipal user,
        AccountRepository repo, IAuthorizationService authz) =>
{
    var account = repo.Find(accountId);
    if (account is null) return Results.NotFound();
    if (!(await authz.AuthorizeAsync(user, account, AccountOperations.Update)).Succeeded) return Results.NotFound();

    if (update.Nickname is { Length: > 40 })
        return Results.Problem(statusCode: 400, title: "Nickname too long");

    var updated = account with { Nickname = update.Nickname };
    repo.Save(updated);
    return Results.Ok(AccountView.From(updated));
}).RequireAuthorization("accounts.write");

app.Run();

// ---------- Domain ----------
public sealed record Account(string AccountId, string CustomerId, string Iban, string Currency,
    string Product, string Status, decimal Balance, string RiskRating, string? Nickname);

// Response DTO: no CustomerId, no RiskRating. Adding a field here is a deliberate review decision.
public sealed record AccountView(string AccountId, string Iban, string Currency, string Product,
    string Status, decimal Balance, string? Nickname)
{
    public static AccountView From(Account a) =>
        new(a.AccountId, a.Iban, a.Currency, a.Product, a.Status, a.Balance, a.Nickname);
}

// Input DTO: unknown JSON properties such as "status" are simply not bound (no mass assignment).
public sealed record AccountUpdate(string? Nickname);

public static class AccountId
{
    public static bool IsValid(string id) =>
        id.Length == 14 && id.StartsWith("ACC-", StringComparison.Ordinal) && id[4..].All(char.IsAsciiDigit);
}

public sealed class AccountRepository
{
    private readonly Dictionary<string, Account> _accounts = new()
    {
        ["ACC-0000123456"] = new("ACC-0000123456", "CUS-00012345", "GB33BUKB20201555555555", "GBP", "current", "open", 1520.40m, "low", null),
        ["ACC-0000123457"] = new("ACC-0000123457", "CUS-00067890", "GB82WEST12345698765432", "GBP", "savings", "open", 8000.00m, "medium", null)
    };
    private readonly Lock _gate = new();

    public Account? Find(string id) { lock (_gate) return _accounts.GetValueOrDefault(id); }
    public IEnumerable<Account> ForCustomer(string customerId) { lock (_gate) return _accounts.Values.Where(a => a.CustomerId == customerId).ToList(); }
    public void Save(Account a) { lock (_gate) _accounts[a.AccountId] = a; }
}

// ---------- Authorisation ----------
public static class AccountOperations
{
    public static readonly OperationAuthorizationRequirement Read = new() { Name = nameof(Read) };
    public static readonly OperationAuthorizationRequirement Update = new() { Name = nameof(Update) };
}

public sealed class AccountOwnerHandler : AuthorizationHandler<OperationAuthorizationRequirement, Account>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
        OperationAuthorizationRequirement requirement, Account resource)
    {
        var sub = context.User.FindFirstValue("sub");
        if (sub is not null && string.Equals(sub, resource.CustomerId, StringComparison.Ordinal))
        {
            if (requirement.Name == nameof(AccountOperations.Update) && resource.Status != "open")
                return Task.CompletedTask; // frozen/closed accounts cannot be changed by customers
            context.Succeed(requirement);
        }
        return Task.CompletedTask;
    }
}

// ---------- Local/test authentication only ----------
public sealed class DevHeaderAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
    ILoggerFactory logger, UrlEncoder encoder) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
    public const string SchemeName = "DevHeader";

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var sub = Request.Headers["X-Test-Sub"].FirstOrDefault();
        if (string.IsNullOrEmpty(sub)) return Task.FromResult(AuthenticateResult.NoResult());
        var scopes = (Request.Headers["X-Test-Scopes"].FirstOrDefault() ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries);
        var claims = new List<Claim> { new("sub", sub) };
        claims.AddRange(scopes.Select(s => new Claim("scope", s)));
        var identity = new ClaimsIdentity(claims, SchemeName);
        return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName)));
    }
}

public partial class Program;
tests/Harbourline.Accounts.Api.Tests/OwnershipTests.cs
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

public sealed class OwnershipTests(WebApplicationFactory<Program> factory) : IClassFixture<WebApplicationFactory<Program>>
{
    private HttpClient ClientFor(string sub, string scopes = "accounts.read accounts.write")
    {
        var c = factory.CreateClient();
        c.DefaultRequestHeaders.Add("X-Test-Sub", sub);
        c.DefaultRequestHeaders.Add("X-Test-Scopes", scopes);
        return c;
    }

    [Fact]
    public async Task Owner_can_read_own_account()
    {
        var res = await ClientFor("CUS-00012345").GetAsync("/accounts/ACC-0000123456", TestContext.Current.CancellationToken);
        Assert.Equal(HttpStatusCode.OK, res.StatusCode);
    }

    [Fact]
    public async Task Other_customer_gets_404_not_403()   // API1
    {
        var res = await ClientFor("CUS-00012345").GetAsync("/accounts/ACC-0000123457", TestContext.Current.CancellationToken);
        Assert.Equal(HttpStatusCode.NotFound, res.StatusCode);
    }

    [Fact]
    public async Task Response_does_not_leak_internal_fields()   // API3
    {
        var json = await ClientFor("CUS-00012345").GetStringAsync("/accounts/ACC-0000123456", TestContext.Current.CancellationToken);
        Assert.DoesNotContain("riskRating", json, StringComparison.OrdinalIgnoreCase);
        Assert.DoesNotContain("customerId", json, StringComparison.OrdinalIgnoreCase);
    }

    [Fact]
    public async Task Patch_ignores_status_field()   // API3 mass assignment
    {
        var client = ClientFor("CUS-00012345");
        var res = await client.PatchAsJsonAsync("/accounts/ACC-0000123456",
            new { nickname = "Bills", status = "closed", balance = 1_000_000m }, TestContext.Current.CancellationToken);
        var body = await res.Content.ReadFromJsonAsync<Dictionary<string, object>>(TestContext.Current.CancellationToken);
        Assert.Equal("open", body!["status"].ToString());
        Assert.Equal("1520.40", body["balance"].ToString());
    }

    [Fact]
    public async Task Missing_scope_is_forbidden()   // API5
    {
        var res = await ClientFor("CUS-00012345", scopes: "profile").GetAsync("/accounts/ACC-0000123456", TestContext.Current.CancellationToken);
        Assert.Equal(HttpStatusCode.Forbidden, res.StatusCode);
    }

    [Fact]
    public async Task Anonymous_is_unauthorised()
    {
        var res = await factory.CreateClient().GetAsync("/accounts", TestContext.Current.CancellationToken);
        Assert.Equal(HttpStatusCode.Unauthorized, res.StatusCode);
    }
}

The test project follows the platform pattern: xUnit v3 4.0.3 on Microsoft.Testing.Platform, OutputType Exe, a project reference to the API and Microsoft.AspNetCore.Mvc.Testing 10.0.15. The full Account Information API in the module project uses the same handler with real Cognito tokens.

Code explained line by line

  1. AddScheme<..., DevHeaderAuthHandler> registers a test-only scheme that reads X-Test-Sub and X-Test-Scopes. In AWS you replace it with AddJwtBearer pointed at the Cognito issuer (or trust claims forwarded by a Lambda authorizer); nothing else changes.
  2. AddPolicy("accounts.read", ...) checks the scope: is this token allowed to read accounts at all? This is function-level authorisation (API5).
  3. SetFallbackPolicy(...) makes every endpoint require an authenticated user unless explicitly marked otherwise. A new route someone forgets to protect is closed, not open.
  4. UseExceptionHandler() plus AddProblemDetails() returns RFC 9457 errors without stack traces (API8).
  5. AccountId.IsValid rejects malformed IDs early. It duplicates the API Gateway model validation on purpose: never assume the edge was configured correctly.
  6. authz.AuthorizeAsync(user, account, AccountOperations.Read) is resource-based authorisation: the decision depends on the loaded object. This single line is the BOLA fix.
  7. Returning Results.NotFound() when authorisation fails hides whether the account exists. Attackers enumerating IDs learn nothing.
  8. repo.ForCustomer(customerId) scopes the list query by the token's sub. The client never passes a customer ID; if it did, you would ignore it.
  9. Math.Clamp(pageSize ?? 20, 1, 100) limits resource consumption (API4) even if the gateway validator is missing.
  10. AccountView is an explicit response contract. Returning the Account entity would leak CustomerId and RiskRating, which is exactly API3 ("excessive data exposure" in the 2019 list).
  11. AccountUpdate(string? Nickname) is the input contract. System.Text.Json ignores extra properties like status and balance, so they cannot be mass-assigned.
  12. AccountOwnerHandler compares sub with CustomerId using ordinal comparison and adds a business rule: customers cannot modify frozen or closed accounts.
  13. The tests encode the security requirements as executable checks. The BOLA test is the one to show an auditor.

Security considerations

⚠ Learning shortcut — not for production

DevHeaderAuthHandler trusts headers the client sends. It exists only so tests can play two customers. Register it only in the Development environment or test host; in production, authentication must come from validated JWTs. Add a startup check that fails if the dev scheme is registered outside Development.

⚠ Learning shortcut — not for production

The lab rolls out WAF rules directly to Block after a short load test. In production, run new rules in Count for at least several days of real traffic, review matches with the API owners, and change to Block through a reviewed IaC change.

  • Rate limits are not authentication or authorisation. A patient attacker can enumerate account IDs under any rate limit. Rate limits buy time; ownership checks stop the leak.
  • Rate keys and IP addresses. Mobile carriers and corporate proxies put many customers behind one IP. Combine IP with route, and consider a key on a header such as an API client ID for partners. If you key on a forwarded IP header, only trust it when a known proxy (CloudFront) sets it.
  • Redact WAF logs. WAF logs contain headers. Redact authorization and any cookie carrying session tokens, and set retention.
  • Unguessable IDs help but are not a control. UUIDs make enumeration harder; they do not replace the ownership check. IDs leak through screenshots, logs and referrers.
  • Error messages. Do not distinguish "account does not exist" from "not yours". Do not echo input in errors without encoding.
  • HTTP APIs. If you choose an HTTP API for cost, you lose WAF at the gateway. Put CloudFront with a WAF web ACL in front, and restrict the HTTP API so it accepts only CloudFront traffic (for example, a secret origin header checked by an authorizer) ⚠ VERIFY your chosen origin-protection pattern.
  • Compliance. Mapping to OWASP is a good engineering practice, not a certification. PCI DSS and UK GDPR obligations need review by your security and compliance teams.

Banking use case

Harbourline's API security standard for every customer-facing API:

  • Design review checklist (filled in per route): owner object; scope required; ownership rule; response DTO fields reviewed; input DTO fields reviewed; page-size limit; business limits; partner calls and their validation.
  • Edge baseline: REST API with a web ACL containing IP reputation, common rule set, known bad inputs, and a per-IP-per-route rate rule; login and payment initiation routes get stricter rate rules and, for browser flows, Bot Control or ACFP where justified by fraud data.
  • Mandatory tests: a cross-customer access test for every route that takes an object ID; a mass-assignment test for every write route.
  • Monitoring: alarm on a spike of 404s per authenticated subject (a BOLA enumeration signal), WAF BlockedRequests, and 401/403 rates.
  • Inventory: every stage and API is tagged with an owner and data classification; untagged APIs fail the IaC pipeline; old stages are deleted when a version is retired.

Common mistakes

  • "We have WAF, so we're covered." WAF cannot see ownership, property exposure or business abuse, which are most of the Top 10.
  • Checking ownership in the list endpoint but not in the single-item endpoint. Attackers go straight to /accounts/{id}.
  • Trusting a customerId from the query string or body. Identity comes from the validated token only.
  • Returning entities. Serialising EF Core entities leaks fields and navigation properties.
  • Managed rules straight to Block. SizeRestrictions_BODY and SQLi rules can block legitimate statement uploads or free-text references.
  • Rate limiting by IP only. Hurts customers behind carrier-grade NAT and barely slows a botnet.
  • Admin routes in the customer API. One missed scope check exposes staff functions (API5).
  • Forgotten stages and versions. The v1 stage without the new authorizer is the door attackers find (API9).

Troubleshooting

SymptomLikely causeFix
WAFInvalidParameterException on createAction used on a managed rule group (needs OverrideAction), or vice versaManaged groups: OverrideAction; own rules: Action
WAFNonexistentItemException on associateWrong stage ARN format or RegionUse arn:aws:apigateway:REGION::/restapis/ID/stages/STAGE and the same Region as the web ACL
Can't associate WAF with the APIIt is an HTTP APIUse a REST API, or CloudFront + WAF in front
Legitimate POSTs get 403 with WAFCommon rule set's body size or XSS ruleCheck WAF logs for terminatingRuleId; override that rule to Count and scope it down
Rate rule never triggers in load testLimit counted per aggregation key over the window; load spread across keys; or rule in CountLower the limit (minimum 10) for the test; check get-rate-based-statement-managed-keys
put-logging-configuration failsLog group name does not start with aws-waf-logs-Rename the log group
Tests: 401 instead of 404 for other customerMissing X-Test-Sub header in the clientUse ClientFor(...) helper
Tests: 200 for other customerOwnership check missing or comparing wrong claimCompare token sub with the resource's CustomerId

Cost and cleanup

  • Free path: the .NET authorisation code and tests run locally at no cost. WAF rule design (the JSON above) can be reviewed without deploying.
  • Credits path: a web ACL with 3 managed groups and 1 rate rule is 1 web ACL + 4 rules = about USD 9 per month, prorated hourly, plus USD 0.60 per million requests. Deploying for 2 hours and sending 50,000 test requests costs a few cents ⚠ VERIFY proration on the WAF pricing page. API Gateway and Lambda traffic in the test fits typical free allowances. CloudWatch Logs ingestion for WAF logs is billed per GB.
  • Do not subscribe to Bot Control, ATP or ACFP for the lab; they have their own monthly fees.

Teardown, in this order:

# 1. Disassociate the web ACL from the stage
aws wafv2 disassociate-web-acl \
  --resource-arn arn:aws:apigateway:us-east-1::/restapis/a1b2c3d4e5/stages/prod \
  --profile learn-sandbox --region us-east-1

# 2. Remove logging, then delete the web ACL (needs the current lock token)
aws wafv2 delete-logging-configuration \
  --resource-arn arn:aws:wafv2:us-east-1:111122223333:regional/webacl/hl-m04-accounts-acl/EXAMPLE-ID \
  --profile learn-sandbox --region us-east-1
TOKEN=$(aws wafv2 get-web-acl --name hl-m04-accounts-acl --scope REGIONAL --id EXAMPLE-ID \
  --query LockToken --output text --profile learn-sandbox --region us-east-1)
aws wafv2 delete-web-acl --name hl-m04-accounts-acl --scope REGIONAL --id EXAMPLE-ID \
  --lock-token "$TOKEN" --profile learn-sandbox --region us-east-1

# 3. Delete the WAF log group
aws logs delete-log-group --log-group-name aws-waf-logs-hl-m04 --profile learn-sandbox --region us-east-1

# 4. Confirm nothing tagged for the platform remains
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
  --query 'ResourceTagMappingList[].ResourceARN' --profile learn-sandbox --region us-east-1

With CDK or Terraform, cdk destroy or terraform destroy does all of this.

Exercises

  • 🟢 Guided: Run the tests. Then delete the authz.AuthorizeAsync check from GET /accounts/{accountId} and run them again. Which test fails, and what HTTP status does the "attacker" now get? Restore the check.
  • 🟡 Challenge: Add GET /accounts/{accountId}/transactions?pageSize= with ownership, a page-size limit and a response DTO that omits idempotency_key and counterparty_iban for card payments. Write the cross-customer test and a test proving pageSize=5000 returns at most 100 items.
  • 🔴 Live problem: Security operations reports: "One authenticated customer made 4,800 requests to /accounts/{id} in 20 minutes from 37 IP addresses, almost all 404." Your WAF rate rule (per IP per route, 300 per 5 min) never fired. Explain why, decide whether customers' data was exposed, and propose two detection and two prevention changes.

Assignment

Produce an OWASP API Top 10 control matrix for your Account Information API: one row per risk, with the control, where it lives (WAF, gateway, code, process), how it is tested, and evidence (test name, IaC file, log query). Commit it next to your OpenAPI document.

Solutions

Knowledge check

Interview questions

  • "What is the number one API security risk and how do you prevent it?" — BOLA: users accessing objects they don't own by changing IDs. Prevent it with an ownership check on every object access, using the identity from the validated token, plus cross-user integration tests. Unguessable IDs and rate limits are secondary.
  • "What would you put in a WAF web ACL for a banking API?" — IP reputation, common rule set, known bad inputs, a rate-based rule keyed on IP and route with a JSON 429, stricter rules on login and payment initiation, logging with redaction; roll out in Count first.
  • "How do you stop mass assignment in ASP.NET Core?" — Bind requests to dedicated input DTOs with only allowed fields; never bind to entities; review DTO changes.
  • "Where do API keys fit?" — Identification and usage-plan quotas for partners, not authentication. Pair them with OAuth, IAM or mTLS.
  • "How would you detect someone enumerating account IDs?" — Access-log metric of 404s per authenticated subject, alarms on spikes, WAF logs correlated by token-derived keys, and fraud review.

Certification practice

Completion checklist

  • I can list the OWASP API Security Top 10 (2023) and give a banking example of each
  • I can explain why WAF cannot stop BOLA and what does
  • I created (or designed) a web ACL with managed groups and a scoped rate-based rule, in Count first
  • My tests prove a customer cannot read or modify another customer's account
  • I use explicit input and response DTOs on every route
  • I ran the cleanup steps and confirmed nothing tagged Project=cea-lab remains

Key takeaways

  • Most OWASP API Top 10 risks are authorisation and business-logic flaws; WAF helps with abuse and volume, not ownership.
  • Enforce ownership on every object access using the token's subject, and return 404 for objects the caller does not own.
  • Explicit response and input DTOs prevent data exposure and mass assignment.
  • Roll out WAF managed rules and rate rules in Count, read the logs, then Block; key rate rules on more than IP alone.
  • REST APIs support WAF directly; HTTP APIs need CloudFront in front.

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