Cloudflare
API Shield · Test Drive

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.

1 Prerequisites

Check what applies to the capabilities you want to try.

  • The zone is on Cloudflare and the API hostname is proxied (orange cloud). Discovery analyzes sampled proxied traffic.
  • API Shield subscription active at account level and assigned to the zone. If it is active only at account level, Discovery does not run for that zone.
  • A way to generate representative traffic from real clients. Traffic sent from a Cloudflare Worker does not count toward Discovery.
  • The session identifier your API really uses is known (cookie, header or JWT claim). Ask the API team.
  • An OpenAPI v3.0.x schema, or permission to learn one from traffic.
  • The JWKS (public keys) of the token issuer, if the API uses JWTs.
  • If needed: for per-session rate limits, Advanced Rate Limiting is required.
  • Beta Sequence mitigation: closed beta, ask your account team. Sequence Analytics does not need it.
  • If your zone uses bot protections, they can challenge scripted clients. Test from a host or path where that is off, or expect extra challenges.

2 Discovery and Endpoint Management

Find the endpoints you did not know you had, and save the ones you want to protect.

What it needs

RequirementValue
Volume per endpointAt least 500 requests within a continuous 10-day period
Response codeThe request must return 2xx from the Cloudflare edge
Traffic sourceNot directly from a Cloudflare Worker
Traffic usedSampled proxied traffic, supported HTTP methods, paths outside /cdn-cgi
SubscriptionAPI Shield, at account and zone level

Operation states

StateMeaning
fullYou saved it, added it manually or created it from a schema. Used for matching, logging, detections and rules.
candidateDiscovered from traffic and matched at the edge. Can already provide context to logs, rules and analytics.
shadowDiscovered 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.

How to do it

  • Send real traffic and wait. No configuration is needed beyond the subscription.
  • Review results in Security → Web Assets → Operations, quick filter Discovered (candidate and shadow).
  • Open the row actions of an operation and select Learn profile to save it (state full).

Test notebook

IDTestExpected
D-1Generate traffic to the three undocumented endpoints (command below), then wait.After enough sampled traffic they appear under Discovered. The documentation does not state how long after the threshold; check at 24 to 48 hours.
D-2Save one discovered operation.State changes to full.
Light traffic to undocumented endpoints (run a few times)
for p in /api/internal/metrics /api/v1/legacy/customers /api/partners/export; do
  curl -s -o /dev/null -w "$p %{http_code}\n" https://{{HOST}}$p
done
One-off curls will not reach 500 requests. A scheduled traffic generator is the way to cross the threshold in a test.

3 Session identifiers

Tell Cloudflare which request value identifies one API client. Several features depend on it.

What they are

  • A value that uniquely identifies an API client: a cookie, an HTTP header, or a claim inside a JWT.
  • Up to 10 can be configured.
  • A JWT claim identifier requires a Token Configuration that verifies the token first.
  • The cookie must comply with RFC 6265, otherwise it is rejected.
  • When the whole Authorization header changes on every login, a claim such as sub or a session id is a more stable identifier.

What depends on them

FeatureWhy it needs a session identifier
Rate limit recommendationsLimits are calculated per session, not per IP
Sequence Analytics and mitigationOrder of requests is tracked per session
Authentication PostureReports whether the identifier is present on successful requests
DiscoveryOptional extra signal

How to do it

  • 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

IDTestExpected
S-1Playground → 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-2Wait 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
R=$(curl -s -X POST https://{{HOST}}/api/login -H 'Content-Type: application/json' -d '{"username":"demo","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"])')
curl -s https://{{HOST}}/api/whoami -H "Authorization: Bearer $TOKEN"
curl -s https://{{HOST}}/api/whoami -H "X-Session-Id: $SID"
curl -s https://{{HOST}}/api/whoami -H "Cookie: lab_session=$SID"

4 Schema validation

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.

How to do it

  • 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}}"
Keep the rule above any Skip rule that covers the same host. A Skip placed first can prevent later rules in the same ruleset from running.

Test notebook

Expected edge results assume the rule above is in Block. With the rule off or in Log, the same requests reach the origin, which answers 422.

IDRequestExpected
SC-1Valid POST /api/customers201 reaches the origin
SC-2Body: invalid tier and a string credit_limit403 edge (origin alone: 422)
SC-3Body: extra field is_admin (mass assignment)403 edge
SC-4Header X-Request-Id is not a UUID403 edge
SC-5Query limit=9999&tier=gold403 edge
SC-6Path /api/customers/abc403 edge
SC-1 to SC-6
H='Content-Type: application/json'; B=https://{{HOST}}
curl -s -o /dev/null -w "SC-1 %{http_code}\n" -X POST $B/api/customers -H "$H" -d '{"name":"Demo","email":"[email protected]","tier":"premium","credit_limit":100}'
curl -s -o /dev/null -w "SC-2 %{http_code}\n" -X POST $B/api/customers -H "$H" -d '{"name":"Evil","email":"[email protected]","tier":"gold","credit_limit":"x"}'
curl -s -o /dev/null -w "SC-3 %{http_code}\n" -X POST $B/api/customers -H "$H" -d '{"name":"M","email":"[email protected]","credit_limit":1,"is_admin":true}'
curl -s -o /dev/null -w "SC-4 %{http_code}\n" -X POST $B/api/customers -H "$H" -H 'X-Request-Id: not-a-uuid' -d '{"name":"D","email":"[email protected]","credit_limit":1}'
curl -s -o /dev/null -w "SC-5 %{http_code}\n" "$B/api/customers?limit=9999&tier=gold"
curl -s -o /dev/null -w "SC-6 %{http_code}\n" $B/api/customers/abc
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

  1. Token Configuration: where to find the JWT and which keys verify it.
  2. A rule that acts on the validation result.

What Cloudflare validates

CheckDetail
Key selectionBy the token kid and alg. No matching key means the token is invalid.
SignatureVerified with the selected key
expValidated if present, with up to 60 seconds of clock skew
nbfValidated if present, same tolerance
Bearer prefixTokens 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.

How to do it

  • 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 ruleWAF custom rule
ScopeHostname plus saved operations; endpoints can be excludedAnything an expression can match
Missing tokenGuided choice: Ignore or Mark as non-compliantYou write it in the expression
ActionsLog or BlockAny WAF action
Reads claims, combines with other signalsNoYes
LogicActs when the expression is falseActs 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.

IDToken kindEdgeOrigin if it arrives
J-1validpass200
J-2expired403 exp401
J-3not_yet_valid403 nbf401
J-4tampered (payload edited to admin)403 signature401
J-5wrong_key403 signature401
J-6unknown_kid403 no matching key401
J-7alg_none (unsigned)403 no matching key401
J-8no_exppass401 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.
  • If confidence is low, start the rule in Log.
  • Requires Enterprise and Advanced Rate Limiting.

Rules

In Security → Security rules → Create rule → Rate limiting rules. Choose the shortest period your plan offers for a demo, and start with action Log.

Matching expression
http.host eq "{{HOST}}" and http.request.method eq "POST" and http.request.uri.path eq "/api/cart/items"
Characteristic (same value counts together)Choose
Session id in a headerHeader value of X-Session-Id
Claim of a valid JWTJWT claim of: token configuration ID and claim sid
Client certificate (mTLS)Header value of Cf-Client-Cert-Sha256 (needs certificate forwarding)
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

IDTestExpected
R-1Fire 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-2Repeat 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
Because the field only checks presence, a client that sends any value in the configured cookie passes. Keep validating the session in the application.

Test notebook

IDTestExpected
A-1Send traffic with and without identifiers to a public route (/api/customers is public in the lab).After the daily scan, a cf-risk-mixed-auth or cf-risk-missing-auth label can appear. The documentation says approximately once a day.

8 Sequence

Learn the order in which clients call your API, then (with the beta) enforce it.

CapabilityAvailabilityWhat it does
Sequence AnalyticsAll API Shield customersGroups the common user journeys per session and scores them (precedence score, estimated from the last 24 hours). Sequences up to 9 operations.
Sequence mitigationClosed beta, EnterpriseFields cf.sequence.current_op, previous_ops, msec_since_op for rules. 10-minute inactivity window; current plus previous nine operations by default.
  • 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

IDTestExpected
Q-1Playground → Sequence → Correct order.201, 200, 200. After traffic accumulates, Sequence Analytics shows the cart, quote, confirm journey.
Q-2Confirm without quote.409 from the origin (no_quote). With sequence mitigation in Block: 403 at the edge.
Q-3Confirm 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.

Rules

Require a valid certificate from your CA (start with Log)
http.host eq "{{HOST}}" and
not (cf.tls_client_auth.cert_verified and cf.tls_client_auth.cert_issuer_ski eq "<ISSUER_SKI>")
Get the issuer SKI from a client certificate
openssl x509 -noout -ext authorityKeyIdentifier -in mtls.crt | tail -n1 | tr -d ': '
Also reject revoked certificates (Cloudflare-managed CA only)
http.host eq "{{HOST}}" and cf.tls_client_auth.cert_revoked
  • Validating the issuer SKI is recommended. Without it, any valid client certificate is accepted whichever CA issued it.
  • Revoked certificates are blocked only if a rule checks for them. Revocation is not checked for BYOCA.
  • Forward the certificate to the origin (Cf-Client-Cert-Sha256, Cf-Client-Cert-Der-Base64) to identify the client in the application or in rate limits.

Safe rollout on an existing production hostname

  1. Pilot on a separate hostname that points to the same origin, with its own certificate.
  2. Enable the rule in Log and check who arrives without a certificate.
  3. Distribute certificates to clients.
  4. 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

IDTestExpected
M-1Request with a valid client certificate.200
M-2Request without a certificate.Blocked (to be confirmed on the pilot).
M-3Request with a certificate from another CA.Blocked by the issuer check.
M-4Revoke 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

  1. Create the rule with action Log.
  2. Send the normal client traffic and the test notebook.
  3. Review Security Events for legitimate requests that would have been blocked.
  4. 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:

SymptomWhere to look
403 with header cf-mitigated: challengeA 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 onlySchema validation rule. Compare with the origin, which answers 422 for the same payload.
403 on a bad tokenService API Shield - Token Validation (native rule, reason shown under Token validation violations) or a custom rule by name.
401, 409, 422The request reached the origin. The application rejected it.
Origin log has no trace of the requestIt was stopped at the edge. The lab origin log records cf_ray so you can match it.
Blocks can come from sources other than custom rules. Read the event Service first, then look for the rule.

11 Results and next steps

What this test drive shows, and where to see the evidence yourself.

GoalWhat it coversWhere to see the evidenceOutcomeCovered
Find the APIs nobody inventoriedDiscovery learns your endpoints from real traffic and lists them as candidate or shadow.Web Assets → Operations → Discovered.Your real API surface becomes visible, including endpoints missing from the documentation.Covered
Know which client is behind each requestSession identifiers: cookie, header and JWT claim (S-1, S-2)/api/whoami and Security Analytics.Per-client visibility that rate limits, sequences and authentication posture build on.Covered
Stop malformed and malicious requests before they reach the APISchema validation: invalid body, extra field, bad header, bad query and bad path (SC-1 to SC-6)Security Events (rule and action). The origin log has no trace of the blocked requests.Invalid requests are stopped at the edge. Valid requests pass untouched.Covered
Reject forged, expired or unsigned tokensJWT validation: tampered, expired, not yet valid, wrong key, unknown key and unsigned tokens (J-1 to J-8)Security Events: service API Shield - Token Validation, with the violation reason.Bad tokens are stopped before they reach your origin. Valid tokens pass.Covered
Contain abuse per client, not per IPRate limiting per session: one session over its limit is stopped while other sessions keep working (R-1, R-2)Security Events: the rate limiting rule and its action. Web Assets shows the suggested limit per operation.The abusive session gets a 429. Other clients are not affected.Covered
Let only known clients and devices inmTLS with a client certificate, an issuer check and a revocation rule.Security Events, which show the rule and the action.Only clients with a valid certificate from your CA reach the API.Covered

Where to look for evidence

  • Security Events: the rule, action and Service that acted on a request (filter by Ray ID).
  • Web Assets: discovered endpoints, saved operations, labels and rate limit recommendations.
  • Origin log: a request that is missing there was stopped at the edge.

Next steps

  • Apply the rules to your real API in Log mode and review the events.
  • Move the rules from Log to Block, endpoint by endpoint.
  • Keep the schema in your release pipeline, and automate schema and JWKS updates with the API or Terraform.
  • Talk to your account team about the plan and any beta features you want to add.
  • Contract the solution, with the modules that matched your goals.
  • Plan the production implementation: scope by hostname and endpoint, rollout order (Log, then Block), change window and owners.