Try API Shield on a live API: what to turn on, what to expect, how to test it
Pick the capabilities that matter for your API. For each one you will find what it needs, how much traffic and time it takes, the rule to write, and a test notebook you can run on this lab API with the Playground. Statements link to the public Cloudflare documentation.
0 Overview and timeline
Use only the sections that match your goals. If you try several capabilities, this order tends to work well: see your API, describe what is valid, then enforce. Traffic volume decides how early each step can start.
1 · Set upSession identifiers, endpoint inventory, schema upload, token configuration. Mostly configuration, done in hours. Changes can take several minutes to apply.
2 · ObserveDiscovery, Sequence Analytics, rate limit recommendations and Authentication Posture learn from real traffic. This is the long phase (days).
3 · LogWrite each rule in Log mode. Review Security Events for false positives.
4 · BlockSwitch the proven rules to Block, one capability at a time.
Detection and mitigation are separate on purpose. Uploading a schema or a token configuration does not block anything by itself: a rule decides the action.
You saved it, added it manually or created it from a schema. Used for matching, logging, detections and rules.
candidate
Discovered from traffic and matched at the edge. Can already provide context to logs, rules and analytics.
shadow
Discovered from traffic but not matched at the edge.
In Cloudflare, shadow means a discovered endpoint that is not matched at the edge. It is not a synonym for "undocumented". This lab serves three endpoints that are absent from the schema on purpose (/api/internal/metrics, /api/v1/legacy/customers, /api/partners/export) so Discovery has something to find.
Security → Settings, filter by API abuse, Session identifiers → Configure session identifiers → Manage identifiers.
Choose the type. For a JWT claim, pick the Token Configuration and type the claim path only, for example sid (the dashboard rejected $.sid in this lab).
After you add or change an identifier, allow at least 24 hours before rate limit recommendations appear.
Test notebook
ID
Test
Expected
S-1
Playground → Session identifiers: log in, then run the cards (all carriers, bearer only, header only, cookie only, anonymous).
Origin/api/whoami lists which carriers arrived and whether they are valid.
S-2
Wait for traffic, then look at Security Analytics for cf.api_gateway.auth_id_present.
True for requests carrying a configured identifier, false for anonymous ones.
Create a session and call whoami with each carrier
Describe what a valid request looks like, and reject everything else before it reaches the origin.
What it needs
An OpenAPI v3.0.x file (.json, .yml or .yaml). v3.1 files can upload if they use v3.0-compatible semantics; v3.1-only semantics are not supported. OpenAPI 2.0 is not supported.
Not supported: validation of responses, external references, non-basic path templating and uniqueItems. Local $ref such as #/components/schemas/Pet works.
Every parameter needs a schema. servers URLs must be absolute.
Bodies are validated for application/json and compatible application/x-www-form-urlencoded. Other content types are accepted without body validation.
Endpoints must exist as saved operations. Uploading in the dashboard adds them automatically.
Auto-generated schemas (for example FastAPI emits 3.1) are often not specific enough. Validate the file in an editor and curate it by hand if the upload fails.
Security → Web Assets → Schema validation → Add validation, upload the file, select Add schema and endpoints. Allow several minutes.
Cloudflare then runs an always-on detection that does not mitigate. Watch it in Profile Analysis first.
Or learn a schema from traffic: Schema learning runs weekly and can be run on demand (Ad-hoc learn schema in Web Assets → Operations). Review it before enforcing: traffic can include bots and scanners.
Rule: block requests that violate the uploaded schema (start with Log)
cf.schema_validation.uploaded.violated and http.host eq "{{HOST}}"
Evidence: Security Events show the rule name and action, and the origin access log does not contain the blocked request. The Playground cards in Schema validation demo run the same cases.
5 JWT validation
Verify tokens at the edge, and decide what to do with the ones that fail.
Two parts
Token Configuration: where to find the JWT and which keys verify it.
A rule that acts on the validation result.
What Cloudflare validates
Check
Detail
Key selection
By the token kid and alg. No matching key means the token is invalid.
Signature
Verified with the selected key
exp
Validated if present, with up to 60 seconds of clock skew
nbf
Validated if present, same tolerance
Bearer prefix
Tokens are verified with or without it
The documented steps do not include the issuer (iss) or audience, so the application should still check them. A token without exp also passes the edge check, so the application should require it too.
Keys are not fetched or refreshed from a JWKS URL. Paste updated keys, or automate with a Worker.
Symmetric keys (HS256) need at least 32 bytes after decoding.
Only JWTs in request headers or cookies are validated, not in a POST body.
Security → Settings, filter by API abuse, Token configurations → Configure tokens. Name it, set the location (header authorization here) and paste the JWKS.
Note the configuration ID (a UUID). Rules use the ID, not the name. List it with GET /zones/{zone_id}/token_validation/config.
Which kind of rule?
API JWT validation rule
WAF custom rule
Scope
Hostname plus saved operations; endpoints can be excluded
Anything an expression can match
Missing token
Guided choice: Ignore or Mark as non-compliant
You write it in the expression
Actions
Log or Block
Any WAF action
Reads claims, combines with other signals
No
Yes
Logic
Acts when the expression is false
Acts when the expression is true
Both validate tokens the same way. Cloudflare recommends custom rules for new policies. Use one or the other for the same endpoints: with both active, it is hard to tell which one blocked.
Custom rule: a token was sent but is invalid (ignores requests with no token)
http.host eq "{{HOST}}" and
any(cf.api_gateway.tokens.presented[*] == "<TOKEN_CONFIG_ID>") and
not any(cf.api_gateway.tokens.valid[*] == "<TOKEN_CONFIG_ID>")
Custom rule: require a valid token (also matches requests with no token)
http.host eq "{{HOST}}" and http.request.uri.path eq "/api/orders" and
not any(cf.api_gateway.tokens.valid[*] == "<TOKEN_CONFIG_ID>")
Place these rules above any Skip rule for the same host.
Test notebook (Token Lab)
The lab mints each token on the server. Protected route: GET /api/orders.
ID
Token kind
Edge
Origin if it arrives
J-1
valid
pass
200
J-2
expired
403 exp
401
J-3
not_yet_valid
403 nbf
401
J-4
tampered (payload edited to admin)
403 signature
401
J-5
wrong_key
403 signature
401
J-6
unknown_kid
403 no matching key
401
J-7
alg_none (unsigned)
403 no matching key
401
J-8
no_exp
pass
401 origin requires exp
J-1 to J-8
B=https://{{HOST}}
for k in valid expired not_yet_valid tampered wrong_key unknown_kid alg_none no_exp; do
T=$(curl -s $B/api/token-lab/$k | python3 -c 'import sys,json;print(json.load(sys.stdin)["token"])')
printf "%-14s" $k; curl -s -o /dev/null -w "%{http_code}\n" $B/api/orders -H "Authorization: Bearer $T"
done
Evidence: blocks from the native rule show the service API Shield - Token Validation with the violation reason. Blocks from a custom rule show the custom rule name. The Playground section JWT validation — Token Lab runs these cases and one more.
6 Rate limiting per session
Limit abuse per client session instead of per IP, and let Cloudflare suggest the threshold.
How the recommendation works
Requests are grouped into 10-minute periods per session. One threshold is recommended per eligible operation.
Calculated from the previous 7 days. Enough eligible traffic is required.
Needs a session identifier; allow at least 24 hours after adding or changing one.
View it in Security → Web Assets → Operations: overall value, p50, p90, p99 and a confidence level. Use the overall recommendation rather than a single percentile.
A rate limiting rule only runs if no earlier Skip rule disables the http_ratelimit phase for that traffic. If a test never triggers, check Skip rules first.
Test notebook
ID
Test
Expected
R-1
Fire many POST /api/cart/items quickly with one session.
First requests 201, then 429 once the limit is exceeded (or a Log event if the action is Log).
R-2
Repeat with a different session (new login).
Counter is separate, so it starts again at 201.
R-1
R=$(curl -s -X POST https://{{HOST}}/api/login -H 'Content-Type: application/json' -d '{"username":"rl-test","password":"pass"}')
TOKEN=$(echo "$R" | python3 -c 'import sys,json;print(json.load(sys.stdin)["access_token"])')
SID=$(echo "$R" | python3 -c 'import sys,json;print(json.load(sys.stdin)["session_id"])')
for i in $(seq 1 15); do
curl -s -o /dev/null -w "%{http_code} " -X POST https://{{HOST}}/api/cart/items \
-H "Authorization: Bearer $TOKEN" -H "X-Session-Id: $SID" -H 'Content-Type: application/json' -d '{"sku":"BOT-ADDON","qty":1}'
done; echo
7 Authentication Posture and endpoint labels
Let Cloudflare tell you which endpoints receive successful requests without an authentication identifier.
After session identifiers are set, successful (2xx) requests are scanned about once a day.
Label cf-risk-missing-auth: all successful requests lack an identifier. Label cf-risk-mixed-auth: some do.
It reports presence, not validity. It does not validate credentials.
Filter by these labels in Web Assets → Operations; the endpoint page shows the identifiers seen over 24 hours or 7 days.
To block anonymous traffic, use a custom rule on cf.api_gateway.auth_id_present.
Rule: no configured session identifier on a protected route
http.host eq "{{HOST}}" and starts_with(http.request.uri.path, "/api/cart") and
not cf.api_gateway.auth_id_present
Needs a session identifier that is unique per user, and operations in full or candidate state.
Workflow: inspect the highest-scoring sequences, confirm with the development team that the last step must always follow the others, then enforce.
With the beta: confirm without a prior quote (replace with the first 8 characters of each operation ID)
http.host eq "{{HOST}}" and
cf.sequence.current_op eq "<CONFIRM_OP_ID_8>" and
not any(cf.sequence.previous_ops[*] == "<QUOTE_OP_ID_8>")
This lab account does not have the mitigation beta, so this rule is shown but not executed here. The origin enforces the same order and answers 409.
Test notebook
ID
Test
Expected
Q-1
Playground → Sequence → Correct order.
201, 200, 200. After traffic accumulates, Sequence Analytics shows the cart, quote, confirm journey.
Q-2
Confirm without quote.
409 from the origin (no_quote). With sequence mitigation in Block: 403 at the edge.
Q-3
Confirm the same quote twice.
409 from the origin. An order rule does not catch replay, because the quote is still in the recent operations.
9 mTLS
Require a client certificate so only known clients and devices reach the API.
Prerequisites
The origin certificate must match the API hostname. Wildcard origin certificates such as *.example.com are not supported for mTLS (the documentation does not explain what breaks, so test it on a pilot host).
A client certificate from the Cloudflare-managed CA (the default) or your own CA (BYOCA, Enterprise).
mTLS enabled for the hostname: SSL/TLS → Client Certificates → Hosts.
Pilot on a separate hostname that points to the same origin, with its own certificate.
Enable the rule in Log and check who arrives without a certificate.
Distribute certificates to clients.
Switch to Block.
The documentation does not state whether a client without a certificate fails during the TLS handshake or reaches the edge and receives a block. Confirm this on the pilot before changing a hostname that real users depend on.
Test notebook
ID
Test
Expected
M-1
Request with a valid client certificate.
200
M-2
Request without a certificate.
Blocked (to be confirmed on the pilot).
M-3
Request with a certificate from another CA.
Blocked by the issuer check.
M-4
Revoke a test certificate and retry.
Blocked by the revocation rule.
Lab status: the mTLS pilot host for this lab is not live yet. Results will be added here once tested.
10 Log first, then Block, and where to look when something is blocked
Turn protections on without breaking legitimate clients, and find the cause quickly when a request is stopped.
Rollout order
Create the rule with action Log.
Send the normal client traffic and the test notebook.
Review Security Events for legitimate requests that would have been blocked.
Change the action to Block, one capability at a time.
Order of rules matters
Block rules go above Skip rules for the same traffic. A Skip can stop later rules from running.
If a test never triggers a rule, check the Skip rules and the phases they disable.
Where did this block come from?
Open Security → Events, filter by the Ray ID (cf-ray response header) and read the Service, the action and the rule. Not every block is a custom rule:
Symptom
Where to look
403 with header cf-mitigated: challenge
A challenge, not a block. It comes from a challenge action or another bot protection, not from API Shield. Find the service in Security Events.
403 on an invalid payload only
Schema validation rule. Compare with the origin, which answers 422 for the same payload.
403 on a bad token
Service API Shield - Token Validation (native rule, reason shown under Token validation violations) or a custom rule by name.
401, 409, 422
The request reached the origin. The application rejected it.
Origin log has no trace of the request
It was stopped at the edge. The lab origin log records cf_ray so you can match it.