[WAF API Security] Your APIs Have a Third Caller: Stop JWT Tampering, BOLA and Prompt Injection with AWS WAF 🛡️🤖

[WAF API Security] Your APIs Have a Third Caller: Stop JWT Tampering, BOLA and Prompt Injection with AWS WAF 🛡️🤖

How to protect APIs from JWT attacks, object enumeration and AI agent abuse. Signature rules cannot see an attack made of perfectly valid API calls. Learn how the new AWS WAF API Security and AI Security managed rule groups catch forged tokens, BOLA, MCP protocol abuse and jailbreak prompts, and how to test them in your own account in under 15 minutes.

📌 Empowering Business: Cloud Network & Edge Services📌 🎯 Subject Matter Expert: WAF & Route 53 🎯

Introduction

For years your APIs had two kinds of callers: your own services, and people clicking through your app. Your app enforced the order, the pace and the input checks.

Now there is a third caller. AI agents read your API description, pick a tool and chain calls directly, with no app in the middle. On top of that, an MCP server or LLM endpoint takes minutes to stand up behind an ALB or CloudFront, often without ever passing through your API gateway or a security review.

The problem? Most API attacks carry no exploit signature at all. An authenticated user asking for someone else's order ID looks exactly like a normal request. A classic WAF rule that inspects one request for a bad pattern cannot tell the difference.

That is the gap the new AWS WAF API Security and AI Security managed rule groups close.

🎯 Three Capabilities, One Story


Note: API Discover option is available in API-GW console under API-Portal
All three work at the same entry points: Amazon CloudFront, Application Load Balancer and Amazon API Gateway REST APIs.

🔍 How API Security Decides

API Security combines two kinds of detection in one rule group.

1. Deterministic rules: judge one request

These read the token in the  Authorization  header and need no learning period. The token itself is the evidence.

💡 Attack-stage rules block, warning and recon rules count. A warning is a posture observation, not an attacker, so blocking it would mean blocking your own integrations.

2. Behavioral detections: judge a caller

These group a client's requests and score its activity against a baseline learned per protected resource. Each finding carries a confidence level:
  • 🟥 High: rules out the known benign explanations. Default: Block.
  • 🟧 Medium: at least one benign explanation still fits. Default: Count.
  • 🟨 Low: rules out none of the benign explanations. Default: Count.
⚠️ Two things that trip everyone up:
1. The first baseline needs about one day of typical traffic, and detections get more accurate over one to two weeks. The JWT rules protect you from day one meanwhile.
2. A caller identified only by IP address (no credential to hash) is never reported at high confidence. So a test script without real tokens will never see a behavioral block. That is by design, not a bug.

AI Security is a second rule group for LLM, MCP and A2A endpoints. It needs an IAM role for Amazon Bedrock Guardrails, so treat it as a separate step. For more here  AI Security 

✅ What You Need First

  • An AWS account you can test in, with AWS CLI v2 configured
  • A CloudFront distribution, ALB or API Gateway REST API to protect
  • For AI Security: a supported Region (US East N. Virginia and Ohio, US West Oregon, Europe London and Stockholm, Asia Pacific Tokyo and Sydney) or CloudFront

🚀 From Zero to Protected

Step 1: Add API Security to your protection pack (web ACL)

Add the rule group last in your rule order (highest priority number) and keep it there:
{
"Name": "APISecurity",
"Priority": 100,
"Statement": {
"ManagedRuleGroupStatement": {
"VendorName": "AWS",
"Name": "AWSManagedRulesAPISecurityRuleSet"
}
},
"OverrideAction": { "None": {} },
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "APISecurity"
}
}

⚠️ For a production rollout, use per-rule  RuleActionOverrides  set to Count, never the rule group's  OverrideAction: Count . With the group override, evaluation stops at the first rule that would block, so later rules never add their labels and you lose the visibility you were trying to get. In the console, Override all rule actions → Count sets the per-rule overrides for you.

Step 2: Turn on logging

You need logs to see labels and CloudWatch metrics to see rates:
aws wafv2 put-logging-configuration --logging-configuration \
"ResourceArn=$ACL_ARN,LogDestinationConfigs=arn:aws:logs:$REGION:$ACCOUNT:log-group:aws-waf-logs-api-demo"

Step 3: Fire some forged tokens 🎯

Here is a small example, standard-library Python script that sends one forged token per attack type:
import base64, json, time, urllib.request, urllib.error
URL = "https://<your-api>/orders/100"
b64 = lambda d: base64.urlsafe_b64encode(json.dumps(d).encode()).rstrip(b"=").decode()
SIG = base64.urlsafe_b64encode(bytes(range(32))).rstrip(b"=").decode() # right size for HS256
SIG256 = base64.urlsafe_b64encode(bytes(range(256))).rstrip(b"=").decode() # right size for RS256
claims = b64({"sub": "user1", "iss": "demo-idp", "exp": int(time.time()) + 3600})
tests = {
"valid looking (expect 200)": f"{b64({'alg':'HS256','typ':'JWT'})}.{claims}.{SIG}",
"alg none (expect 403)": f"{b64({'alg':'none','typ':'JWT'})}.{claims}.",
"embedded jwk (expect 403)": f"{b64({'alg':'RS256','jwk':{'kty':'RSA','n':'abc','e':'AQAB'}})}.{claims}.{SIG256}",
"remote jku (expect 403)": f"{b64({'alg':'RS256','jku':'https://example.invalid/jwks'})}.{claims}.{SIG256}",
"kid traversal (expect 403)": f"{b64({'alg':'HS256','kid':'../../keys/signing.key'})}.{claims}.{SIG}",
}
for name, tok in tests.items():
req = urllib.request.Request(URL, headers={"Authorization": f"Bearer {tok}"})
try:
code = urllib.request.urlopen(req).status
except urllib.error.HTTPError as e:
code = e.code
print(f"{code} {name}")

⚠️ Test only your own API, in a test environment first. These tokens are fake and carry no real credentials. AWS WAF checks the structure of a token, not its signature, so a forged-looking token with a made-up signature is enough to trigger the rules.
💡 Use a route that has no signature-checking authorizer. With one, the valid-looking token returns  401  and the forged tokens still return  403 . If you set the Count overrides from Step 1, all five return  200  and the evidence is in the labels (Step 4).

Step 4: See exactly what AWS WAF decided 🔍

In CloudWatch Logs Insights, against your WAF log group:
fields @timestamp, action, terminatingRuleId, httpRequest.uri
| parse @message /"labels":\[(?<lbl>[^\]]*)\]/
| filter lbl like /api-security/
| stats count() by action, lbl
| sort count() desc
Every request shows its rule and its label. 🎤

Step 5: Act on a label with your own rule

Labels are available to rules after the rule group. For example, to block medium-confidence object level findings on a sensitive API:
{
"Name": "BlockObjectLevelMedium",
"Priority": 110,
"Action": { "Block": {} },
"Statement": {
"LabelMatchStatement": {
"Scope": "LABEL",
"Key": "awswaf:managed:aws:api-security:attack:object_level:medium"
}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "ObjLvlMedium"
}
}

🧭 Rolling It Out Safely

  1. Count first. Override the blocking rules to Count with rule action overrides.
  1. Put it last and leave it there. Behavioral detections learn from the traffic that reaches them.
  1. Wait. About a day for first findings; judge them after one to two weeks. Don't tune in the first few days.
  1. Rank by rate, confirm in logs. A steady, traffic-proportional match rate is the shape of a false positive. A burst from near zero is the shape of an attack.
  1. Scope down to your API paths so static content and your web front end are not evaluated (and not billed).
  1. Enforce by removing the Count overrides. Promote a medium rule only one detection at a time, where your metrics support it.

🧪 When Good Traffic Looks Bad: False Positives

A false positive here is traffic you want to serve, matched by a rule that is working as designed. The behavioral detections compare each client to the pattern learned for your endpoints, and some legitimate clients simply don't behave like your typical users.
First, know what you can't change: the rule group has no configuration of its own. There is no sensitivity knob and no switch to turn off one detection.
You have exactly three levers:
✅ Override a rule's action (for example, keep  APISecurityObjectLevelHigh  at Count while you investigate)
✅ Scope down what the rule group evaluates
✅ Add your own rule before or after the rule group
The three cases you are most likely to hit are a nightly job that reads many IDs, your own security scanner, and a client on an old API version. For each one,  confirm the caller in the logs first , because a credential stuffing campaign and a batch job look almost the same in a metric and very different in a log line.

💬 The Shift

Your security team just went from "every request was 200, so we never saw it" to "here is the caller, here is the label, here is the confidence, and it was blocked across every endpoint." 🎤⬇️


📚 Further readings

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article