---
title: Cloudflare API Shield
description: APIs have become the backbone of popular web services, helping the Internet become more accessible and useful.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/index.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Cloudflare API Shield

Identify and address your API vulnerabilities.

 Enterprise-only paid add-on 

Note

Enterprise customers can preview this product as a [non-contract service](https://developers.cloudflare.com/billing/preview-services/), which provides full access, free of metered usage fees, limits, and certain other restrictions.

## Why care about API security?

APIs have become the [backbone of popular web services ↗](https://blog.postman.com/intro-to-apis-history-of-apis/), helping the Internet become more accessible and useful.

As APIs have become more prevalent, however, so have their problems:

* Many companies have [thousands of APIs](https://developers.cloudflare.com/api-shield/security/api-discovery/), including ones they do not even know about.
* To support a large base of users, many APIs are protected by a negative security model that makes them vulnerable to credential-stuffing attacks and automated scanning tools.
* With so many endpoints and users, it’s difficult to recognize brute-force attacks against [specific endpoints](https://developers.cloudflare.com/api-shield/security/volumetric-abuse-detection/).
* Sophisticated attacks are even harder to recognize, often because even development teams are unaware of common and uncommon [usage patterns](https://developers.cloudflare.com/api-shield/security/sequence-analytics/).

Refer to the [Get started](https://developers.cloudflare.com/api-shield/get-started/) guide to set up API Shield.

## Features

### Security features

Secure your APIs using API Shield's security features.

[ Use Security features ](https://developers.cloudflare.com/api-shield/security/) 

### Management, monitoring, and more

Monitor the health of your API endpoints.

[ Use Management, monitoring, and more ](https://developers.cloudflare.com/api-shield/management-and-monitoring/) 

## Availability

Cloudflare API Security products are available to Enterprise customers only, though anyone can set up [Mutual TLS](https://developers.cloudflare.com/api-shield/security/mtls/) with a Cloudflare-managed certificate authority.

The full API Shield security suite is available as an Enterprise-only paid add-on, but all customers can access [Endpoint Management](https://developers.cloudflare.com/api-shield/management-and-monitoring/) and [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/) functionalities.

Note

API Shield currently does not work for JDCloud customers.

## Related products

**[DDoS Protection](https://developers.cloudflare.com/ddos-protection/)** 

Cloudflare DDoS protection secures websites, applications, and entire networks while ensuring the performance of legitimate traffic is not compromised.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}}]}
```

---

---
title: Get started with API Shield
description: This guide will help you set up API Shield to identify and address API security best practices.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/get-started.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Get started with API Shield

This guide will help you set up API Shield to identify and address API security best practices.

Note

Enabling API Shield features will have no impact on your traffic until you choose to move a setting from `log` to `block` mode.

## Session identifiers

While not strictly required, it is recommended that you configure your session identifiers when getting started with API Shield. When Cloudflare inspects your API traffic for individual sessions, we can offer more tools for visibility, management, and control.

If you are unsure of the session identifiers that your API uses, consult with your development team.

Session identifiers should uniquely identify API clients. A common session identifier for API traffic is the `Authorization` header. When a [JSON Web Token (JWT)](https://developers.cloudflare.com/api-shield/security/jwt-validation/) is used by the API for client authentication, its value may change over time. You can use a claim value inside the JWT such as `sub` or `email` as a session ID to uniquely identify the session over time.

If your API uses the `Authorization` header on more than 1% of successful requests to your zone, Cloudflare will automatically set it as the API Shield session identifier.

You must have specific entitlements to configure session identifiers or cookies as a form of identifiers, such as an Enterprise subscription, for features such as [API Discovery](https://developers.cloudflare.com/api-shield/security/api-discovery/), [Sequence Mitigation](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/) or [rate limiting recommendations](https://developers.cloudflare.com/api-shield/security/volumetric-abuse-detection/), and to see results in [Sequence Analytics](https://developers.cloudflare.com/api-shield/security/sequence-analytics/) and [Authentication Posture](https://developers.cloudflare.com/api-shield/security/authentication-posture/).

### To set up session identifiers

* [  New dashboard ](#tab-panel-3126)
* [ Old dashboard ](#tab-panel-3127)

1. In the Cloudflare dashboard, go to the **Security Settings** page.  
[ Go to **Settings** ](https://dash.cloudflare.com/?to=/:account/:zone/security/settings)
2. Filter by **API abuse**.
3. On **Session identifiers**, select **Configure session identifiers**.
4. Select **Manage identifiers**.
5. Choose the type of session identifier (cookie, HTTP header, or JWT claim).  
Note  
The session identifier cookie must comply with RFC 6265\. Otherwise, it will be rejected.  
If you are using a JWT claim, choose the [Token Configuration](https://developers.cloudflare.com/api-shield/security/jwt-validation/api/#token-configurations) that will verify the JWT. Token Configurations are required to use JWT claims as session identifiers. Refer to [JWT Validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/) for more information.
6. Enter the name of the session identifier.
7. Select **Save**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/login), and select your account and domain.
2. Go to **Security** \> **API Shield**.
3. Select **Settings**.
4. On **Endpoint settings**, select **Manage identifiers**.
5. Choose the type of session identifier (cookie, HTTP header, or JWT claim).  
Note  
The session identifier cookie must comply with RFC 6265\. Otherwise, it will be rejected.  
If you are using a JWT claim, choose the [Token Configuration](https://developers.cloudflare.com/api-shield/security/jwt-validation/api/#token-configurations) that will verify the JWT. Token Configurations are required to use JWT claims as session identifiers. Refer to [JWT Validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/) for more information.
6. Enter the name of the session identifier.
7. Select **Save**.

After setting up session identifiers and allowing some time for Cloudflare to learn your traffic patterns, you can view your per endpoint and per session rate limiting recommendations, as well as enforce per endpoint and per session rate limits by creating new rules. Session identifiers will allow you to view API Discovery results from session ID-based discovery and session traffic patterns in Sequence Analytics.

## Upload a schema using Schema validation (optional)

Schema validation protects your APIs by ensuring only requests matching your API schema are allowed to communicate with your origin.

While not strictly required, uploading a pre-existing schema will offer the chance to automatically add endpoints to Endpoint Management. If you already have a schema, you can upload it to [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/).

Note

It is recommended to start with Schema validation rules set to `log` to review logged requests in [Security Events](https://developers.cloudflare.com/waf/analytics/security-events/). When you are confident that only the correct requests are logged, you should switch the rule to `block`.

If you do not have a schema to upload, continue reading this guide to learn how to generate a schema with API Shield.

## Enable the Sensitive Data Detection ruleset and accompanying rules

API Shield works with Cloudflare WAF’s [Sensitive Data Detection](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/#sensitive-data-detection) ruleset to identify API endpoints that return sensitive data such as social security or credit card numbers in their HTTP responses. Monitoring these endpoints can be critical to ensuring sensitive data is returned only when expected.

Note

A subscription is required for Sensitive Data Detection. Contact your account team if you are not entitled for Sensitive Data Detection.

You can identify endpoints returning sensitive data by selecting the icon next to the path in a row. Expand the endpoint to see details on which rules were triggered and view more information by exploring events in **Firewall Events**.

## Add your discovered endpoints to Endpoint Management

Cloudflare’s machine learning models have already inspected your existing traffic for the presence of API endpoints. By adding endpoints from API Discovery to Endpoint Management, you can unlock further security, visibility, and management features of the platform. Endpoint Management monitors the health of your API endpoints by saving, updating, and monitoring performance metrics.

Note

Schema validation, schema learning, JWT validation, Sequence Analytics, sequence mitigation, and rate limit recommendations only run on endpoints saved to Endpoint Management.

You can save your endpoints directly from [API Discovery](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/#add-endpoints-from-api-discovery), [Schema validation](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/#add-endpoints-from-schema-validation), or [manually](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/#add-endpoints-manually) by method, path, and host.

This will add the specified endpoints to your list of managed endpoints. You can view your list of saved endpoints in the **Endpoint Management** page.

Cloudflare will aggregate [performance data](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/#endpoint-analysis) and security data on your endpoint once it is saved.

### Allow the system to learn your traffic patterns

Cloudflare will inspect your API traffic and begin to learn its schema over the next 24 hours after adding an endpoint. Depending on how much traffic an individual endpoint sees, our confidence in the resulting schema may differ.

Cloudflare will also use the configured session identifiers to suggest rate limits per endpoint.

For best results, allow at least 24 hours after adding endpoints before proceeding to the following steps.

We recommend proceeding with [additional configurations](https://developers.cloudflare.com/api-shield/get-started/#additional-configuration) if this is your first time setting up API Shield and have added your first API endpoints to Endpoint Management.

## Add rate limits to your most sensitive endpoints

[Rate limiting rules](https://developers.cloudflare.com/waf/rate-limiting-rules/) allow you to define rate limits for requests matching an expression, and choose the action to perform when those rate limits are reached.

You can observe Cloudflare suggested rate limits in Endpoint Management for endpoints using session identifiers. Unlike many security tools, these recommended rate limits are per-endpoint and per-session, not site-wide and not based on IP address. When creating a rule, it will be based on only traffic to that specific endpoint from unique visitors during their session. This feature allows you to be very specific and targeted with your rate limit enforcement, both lowering abusive traffic and false positives due to broadly scoped rules.

## Import a learned schema to Schema validation

Cloudflare learns schema parameters via traffic inspection for all endpoints stored in Endpoint Management. You can export OpenAPI schemas in OpenAPI v3.0.0 format by hostname.

By importing the learned schema, you can protect API endpoints found via API Discovery that were never previously possible to protect due to not knowing about their presence or schema.

You can import the learned schema of an entire hostname using the [Cloudflare dashboard](https://developers.cloudflare.com/api-shield/security/schema-validation/#add-validation-by-applying-a-learned-schema-to-an-entire-hostname). Alternatively, you can [apply learned schemas to individual endpoints](https://developers.cloudflare.com/api-shield/security/schema-validation/#add-validation-by-applying-a-learned-schema-to-a-single-endpoint). Before applying the learned schema, Cloudflare suggests exporting the schema to review what will validate your traffic.

## Export a learned schema from Endpoint Management

Learned schemas will always include the listed hostname in the servers section, all endpoints by host, method, and path, and detected path variables. They can also potentially include detected query parameters and their format. You can optionally include API Shield's rate limit threshold recommendations.

You can export your learned schemas in the [Cloudflare dashboard](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/schema-learning/#export-a-schema) or via the [API](https://developers.cloudflare.com/api/resources/api%5Fgateway/subresources/schemas/methods/list/).

## View and configure Sequence Analytics

[Sequence Analytics](https://developers.cloudflare.com/api-shield/security/sequence-analytics/) surfaces a subset of important API request sequences found in your API traffic over time.

You can observe the top sequences in your API traffic that contain endpoints stored in Endpoint Management. We rank sequences by Correlation Score. High-scoring sequences contain API requests which are likely to occur together in order.

[Sequence mitigation](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/) allows you to enforce request patterns for authenticated clients communicating with your API. Use Sequence Analytics to better understand the request sequences used by your API clients.

You should apply all possible API Shield protections (rate limiting suggestions, Schema validation, JWT validation, and mTLS) to API endpoints found in high correlation score sequences that make up the critical request flows in your application. You should also check their specific endpoint order with your development team.

For more information, refer to [Detecting API abuse automatically using sequence analysis ↗](https://blog.cloudflare.com/api-sequence-analytics) blog post.

## Additional configuration

### Set up JSON Web Tokens (JWT) validation

Use the Cloudflare API to configure [JSON Web Tokens validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/), which validates the integrity and validity of JWTs sent by clients to your API or web application.

### Set up GraphQL Malicious Query Protection

If your origin uses GraphQL, you may consider setting limits on GraphQL query size and depth.

[GraphQL malicious query protection](https://developers.cloudflare.com/api-shield/security/graphql-protection/api/) scans your GraphQL traffic for queries that could overload your origin and result in a denial of service. Customers can build rules that limit the query depth and size of incoming GraphQL queries in order to block suspiciously large or complex queries.

For more information, refer to the [blog post ↗](https://blog.cloudflare.com/protecting-graphql-apis-from-malicious-queries/).

### Mutual TLS (mTLS) authentication

If you operate an API that requires or would benefit from an extra layer of protection, you may consider using Mutual TLS (mTLS).

[Mutual TLS (mTLS) authentication](https://developers.cloudflare.com/api-shield/security/mtls/) uses client certificates to ensure traffic between client and server is bidirectionally secure and trusted. mTLS also allows requests that do not authenticate via an identity provider, such as Internet-of-things (IoT) devices, to demonstrate they can reach a given resource.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/get-started/","name":"Get started with API Shield"}}]}
```

---

---
title: Plans
description: Free, Pro, Business, and Enterprise customers without an API Shield subscription can access Endpoint Management and Schema validation, but no other API Shield features.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/plans.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Plans

Free, Pro, Business, and Enterprise customers without an API Shield subscription can access [Endpoint Management](https://developers.cloudflare.com/api-shield/management-and-monitoring/) and [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/), but no other [API Shield](https://developers.cloudflare.com/api-shield/) features.

To subscribe to API Shield, upgrade to an Enterprise plan and contact your account team.

Limits to endpoints apply to Endpoint Management and Schema validation. Refer to the table below for limits based on your zone plan.

| Plan type                         | Saved endpoints | Uploaded schemas | Total uploaded schema size | Rule action  |
| --------------------------------- | --------------- | ---------------- | -------------------------- | ------------ |
| **Free**                          | 100             | 5                | 200 kB                     | Block only   |
| **Pro**                           | 250             | 5                | 500 kB                     | Block only   |
| **Business**                      | 500             | 10               | 2 MB                       | Block only   |
| **Enterprise without API Shield** | 500             | 10               | 5 MB                       | Log or Block |
| **Enterprise with API Shield**    | 10,000          | 10+              | 10+ MB                     | Log or Block |

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/plans/","name":"Plans"}}]}
```

---

---
title: Security
description: Cloudflare offers the following features to help secure your APIs:
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/index.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Security

Cloudflare offers the following features to help secure your APIs:

| Discovery & management                                                                                                         | Posture management                                                                                                  | Runtime protection                                                                                |
| ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| [API Discovery](https://developers.cloudflare.com/api-shield/security/api-discovery/)                                          | [Volumetric Abuse Detection](https://developers.cloudflare.com/api-shield/security/volumetric-abuse-detection/)     | [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/)     |
| [Schema learning](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/schema-learning/) | [Authentication Posture](https://developers.cloudflare.com/api-shield/security/authentication-posture/)             | [JWT validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/)           |
| [Sequence Analytics](https://developers.cloudflare.com/api-shield/security/sequence-analytics/)                                | [BOLA vulnerability detection](https://developers.cloudflare.com/api-shield/security/bola-vulnerability-detection/) | [Sequence mitigation](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/) |
| [Risk labels](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-labels/#risk-labels)             | [Mutual TLS (mTLS)](https://developers.cloudflare.com/api-shield/security/mtls/)                                    |                                                                                                   |
| [Vulnerability Scanner](https://developers.cloudflare.com/api-shield/security/vulnerability-scanner/)                          | [GraphQL query protection](https://developers.cloudflare.com/api-shield/security/graphql-protection/)               |                                                                                                   |

## Example Cloudflare solutions

Cloudflare's API Shield — together with other compatible Cloudflare products — helps protect your API from the issues detailed in the [OWASP® API Security Top 10 ↗](https://owasp.org/www-project-api-security/).

The following table provides examples of how you might match Cloudflare products to OWASP vulnerabilities:

| OWASP issue                                     | Example Cloudflare solution                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Broken Object Level Authorization               | [BOLA vulnerability detection](https://developers.cloudflare.com/api-shield/security/bola-vulnerability-detection/), [Sequence mitigation](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/), [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/), [JWT validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/), [Rate Limiting](https://developers.cloudflare.com/waf/rate-limiting-rules/), [Vulnerability Scanner](https://developers.cloudflare.com/api-shield/security/vulnerability-scanner/) |
| Broken Authentication                           | [Authentication Posture](https://developers.cloudflare.com/api-shield/security/authentication-posture/), [mTLS](https://developers.cloudflare.com/api-shield/security/mtls/), [JWT validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/), [Exposed Credential Checks](https://developers.cloudflare.com/waf/managed-rules/check-for-exposed-credentials/), [Bot Management](https://developers.cloudflare.com/bots/)                                                                                                                                                  |
| Broken Object Property Level Authorization      | [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/), [JWT validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/)                                                                                                                                                                                                                                                                                                                                                                                                             |
| Unrestricted Resource Consumption               | [Rate Limiting](https://developers.cloudflare.com/waf/rate-limiting-rules/), [Sequence mitigation](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/), [Bot Management](https://developers.cloudflare.com/bots/), [GraphQL Query Protection](https://developers.cloudflare.com/api-shield/security/graphql-protection/)                                                                                                                                                                                                                                                   |
| Broken Function Level Authorization             | [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/), [JWT validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/)                                                                                                                                                                                                                                                                                                                                                                                                             |
| Unrestricted Access to Sensitive Business Flows | [Sequence mitigation](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/), [Bot Management](https://developers.cloudflare.com/bots/), [GraphQL Query Protection](https://developers.cloudflare.com/api-shield/security/graphql-protection/)                                                                                                                                                                                                                                                                                                                                |
| Server Side Request Forgery                     | [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/), [WAF managed rules](https://developers.cloudflare.com/waf/managed-rules/), [WAF custom rules](https://developers.cloudflare.com/waf/custom-rules/)                                                                                                                                                                                                                                                                                                                                                  |
| Security Misconfiguration                       | [Sequence mitigation](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/), [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/), [WAF managed rules](https://developers.cloudflare.com/waf/managed-rules/), [GraphQL Query Protection](https://developers.cloudflare.com/api-shield/security/graphql-protection/)                                                                                                                                                                                                                 |
| Improper Inventory Management                   | [Discovery](https://developers.cloudflare.com/api-shield/security/api-discovery/), [Schema learning](https://developers.cloudflare.com/api-shield/management-and-monitoring/#endpoint-schema-learning)                                                                                                                                                                                                                                                                                                                                                                                             |
| Unsafe Consumption of APIs                      | [JWT validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/), [WAF managed rules](https://developers.cloudflare.com/waf/managed-rules/)                                                                                                                                                                                                                                                                                                                                                                                                                                 |

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}}]}
```

---

---
title: API Discovery
description: Most development teams struggle to keep track of their APIs. Cloudflare API Discovery helps you map out and understand your attack surface area.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/api-discovery.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# API Discovery

Most development teams struggle to keep track of their APIs. Cloudflare API Discovery helps you map out and understand your attack surface area.

## Process

Cloudflare produces a simple, trustworthy map of API endpoints through a process of path normalization.

For example, you might have thousands of APIs, but a lot of the calls look similar, such as:

* `api.example.com/profile/238`
* `api.example.com/profile/392`

Both paths serve a similar purpose — allowing users to log in to their accounts — but they are not identical. To simplify your endpoints, these examples might both map to `api.example.com/profile/*`.

API Discovery runs this process across all your traffic, generating a simple map of endpoints that might look like:

```

/api/login/{customer_identifier}

/api/auth

/api/account/{customer_identifier}

/api/password_reset

/api/logout


```

Similarly, if you have multiple subdomains that share the same set of endpoints, Cloudflare will consolidate subdomains:

```

us-api.example.com/api/v1/users/{var1}

de-api.example.com/api/v1/users/{var1}

fr-api.example.com/api/v1/users/{var1}

jp-api.example.com/api/v1/users/{var1}


```

We will consolidate to `{hostVar1}.example.com/api/v1/users/{var1}`.

For more technical details, see our [blog post ↗](https://blog.cloudflare.com/ml-api-discovery-and-schema-learning/).

### Inbox view

API Shield first catalogs your discovered API endpoints in an email inbox-style view. From API Discovery, you can save endpoints to [Endpoint Management](https://developers.cloudflare.com/api-shield/management-and-monitoring/) or ignore endpoints to remove them from view.

You should save all discovered API endpoints to Endpoint Management while ignoring any potential false positives in the API Discovery results by selecting **Save** or **Ignore** on each line. Alternatively, you can bulk-select endpoints to save or ignore. You can get started with saving endpoints by saving all endpoints with a variable. Search for `var1` in the search box and add all the resulting endpoints. You can examine endpoints without path variables for accuracy later on.

By adding endpoints to Endpoint Management, you will unlock further [security](https://developers.cloudflare.com/api-shield/security/), [visibility](https://developers.cloudflare.com/api-shield/management-and-monitoring/#endpoint-analysis), and [management](https://developers.cloudflare.com/api-shield/management-and-monitoring/) features of the platform. Endpoint Management monitors the health of your API endpoints by saving, updating, and monitoring performance metrics.

To restore any errantly ignored endpoints, you can filter by **Ignored** and select **Restore**.

API Discovery is an ongoing process. Check back regularly for new API Discovery results. A badge with the number of endpoints needing review will show in the API Shield dashboard. You may see the quantities in the **Needs Review** and **Ignored** metrics change over time. As your actual API or traffic patterns to your APIs change, API Discovery results that are not saved can disappear.

Note

Cloudflare will use your feedback on the ignored endpoints to better train the API Discovery Machine Learning model in a future release.

### Machine Learning-based Discovery

Your API endpoints are discovered with both the Session Identifier-based Discovery and the Machine Learning-based Discovery.

To access Machine Learning-based Discovery:

* [  New dashboard ](#tab-panel-3156)
* [ Old dashboard ](#tab-panel-3157)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Go to the **Discovery** tab.
3. Filter the source results by `Session Identifier` or `Machine Learning` to view results from each Discovery method.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Go to **API Shield** \> **Discovery**.
3. Filter the source results by `Session Identifier` or `Machine Learning` to view results from each Discovery method.

If all of your zone’s API traffic contains the session identifier that you have configured, both sources may deliver the same results due to similarities between their underlying methodology. We expect Machine Learning-based Discovery to excel in discovering API traffic regardless of whether your API uses a session identifier.

You can direct any feedback about your API Discovery results to your account team.

## Requirements

To ensure your API endpoints are successfully discovered and mapped by Cloudflare, traffic to the endpoint must meet specific operational criteria.

If an endpoint does not appear in the Discovery inbox, it is typically because the system has not observed enough valid requests over a continuous period. API Discovery only processes requests that satisfy all of the following requirements:

* The request must return a `2xx` response code from the Cloudflare edge.
* The request must not come directly from Cloudflare Workers.
* The endpoint must receive at least 500 requests within a 10-day period.

Endpoints discovered using session identifiers will be labeled as such in the Cloudflare dashboard. If the endpoints are not discovered through session identifiers, they will be discovered using our machine learning-based [API Discovery](https://developers.cloudflare.com/api-shield/security/api-discovery/).

## Availability

API Discovery is only available for Enterprise customers. If you are an Enterprise customer interested in this product, contact your account team.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/api-discovery/","name":"API Discovery"}}]}
```

---

---
title: Authentication Posture
description: Authentication Posture helps users identify authentication misconfigurations for APIs and alerts of their presence.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/authentication-posture.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Authentication Posture

Authentication Posture helps users identify authentication misconfigurations for APIs and alerts of their presence.

For example, a security team member may believe that their API hosted at `/api/v1/users` and `/api/v1/orders` are guarded by the fact that only authenticated users can interact with the endpoints. However, bugs in origin API authentication policies may lead to broken authentication vulnerabilities. Authentication Posture with API Shield details the authentication status of successful requests to your API endpoints, alerting to potential misconfigurations.

Consider a typical e-commerce application. Users can browse items and prices without being logged in. However, to retrieve order details with the `GET /api/v1/orders/{order_id}` endpoint, this example application requires users to log in to their account and pass the subsequent Authorization HTTP header in all requests. Cloudflare will alert via [Security Center Insights](https://developers.cloudflare.com/security-center/security-insights/) and [Endpoint labels](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-labels/) if successful requests are sent to the `GET /api/v1/orders/{order_id}` endpoint or any other endpoint without authentication when session identifiers are configured.

## Process

After configuring [session identifiers](https://developers.cloudflare.com/api-shield/get-started/#session-identifiers), API Shield continuously scans your traffic for successful requests without authentication and labels your endpoints on a daily basis. Refer to the table below for our labeling methodology.

| Description                                                                        | 2xx response codes | 4xx, 5xx response codes                               |
| ---------------------------------------------------------------------------------- | ------------------ | ----------------------------------------------------- |
| If all requests are missing authentication, Cloudflare will apply the label:       | cf-missing-auth    | Without successful responses, no label will be added. |
| If only some requests are missing authentication, Cloudflare will apply the label: | cf-mixed-auth      | Without successful responses, no label will be added. |

### Examine an endpoint's authentication details

* [  New dashboard ](#tab-panel-3158)
* [ Old dashboard ](#tab-panel-3159)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Go to the **Endpoints** tab.
3. Filter your endpoints by the `cf-risk-missing-auth` or `cf-risk-mixed-auth` labels.
4. Select an endpoint to see its authentication posture details on the endpoint details page.
5. Choose between the 24-hour and 7-day view options, and note any authentication changes over time.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Go to **Security** \> **API Shield** \> **Endpoint Management**.
3. Filter Endpoint Management by the `cf-risk-missing-auth` or `cf-risk-mixed-auth` labels.
4. Select an endpoint to see its authentication posture details on the endpoint details page.
5. Choose between the 24-hour and 7-day view options, and note any authentication changes over time.

The main authentication widget displays how many successful requests over the last seven days had session identifiers included with them, and which identifiers were included with the traffic.

The authentication-over-time chart shows a detailed breakdown over time of how clients successfully interacted with your API and which identifiers were used. A large increase in unauthenticated traffic may signal a security incident. Similarly, any successful unauthenticated traffic on an endpoint that is expected to be 100% authenticated can be a cause for concern.

Work with your development team to understand which authentication policies may need to be corrected on your API to stop unauthenticated traffic.

### Stop unauthenticated traffic with Cloudflare

You can use the `cf.api_gateway.auth_id_present` field in [custom rules](https://developers.cloudflare.com/waf/custom-rules/) to trigger when the API Shield configured session identifiers are present or absent on a request. Since this rule would cover your entire zone, Cloudflare recommends adding a host and path match in the rule to pinpoint the protection to exactly what is needed.

## Limitations

Authentication Posture can only apply when customers accurately set up session identifiers in API Shield. As a reminder, session identifiers are meant to uniquely identify authenticated users of your API. If you are unsure of your API's session identifier, consult with your development team.

## Availability

Authentication Posture is available for all Enterprise customers with an API Shield subscription.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/authentication-posture/","name":"Authentication Posture"}}]}
```

---

---
title: Broken Object Level Authorization vulnerability detection
description: A Broken Object Level Authorization (BOLA) vulnerability is where an application or API fails to properly verify if a user has permission to access specific data.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/bola-vulnerability-detection.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Broken Object Level Authorization vulnerability detection

A Broken Object Level Authorization (BOLA) vulnerability is where an application or API fails to properly verify if a user has permission to access specific data.

Bugs in the application or API allow attackers to bypass authorization checks and access potentially sensitive information by manipulating and iterating through object identifiers.

Vulnerabilities can occur at any time, including in the original application's deployment. However, changes or upgrades to authentication and authorization policies can also introduce these bugs.

BOLA vulnerabilities are as dangerous as an account takeover. Successfully exploiting a BOLA vulnerability allows the attacker to access or change data that they should not have ownership over.

Cloudflare labels endpoints with BOLA risk when we detect two distinct signals common with attacks exploiting BOLA: **Parameter pollution** and **Enumeration**.

## Enumeration

Cloudflare continually profiles all sessions on a per-endpoint basis and detects anomalous sessions that successfully request many unique data points from an API endpoint against what is normal.

Note

Sessions that have more random behavior or repetition have a higher chance of triggering an alert.

The BOLA enumeration label requires an endpoint to have seen at least 10,000 sessions before being eligible for outlier detection.

Enumeration example

**Endpoint**: `GET /api/v1/users/{userId}/credit-cards`

* **Normal behavior**: Users request credit cards using only their own `userId`.
* **Attack behavior**: Attackers request hundreds of `userId` values per session by brute-force iterating through `userIds` found via other methods.
* **Result**: If the origin authorization policy is broken for this endpoint, the attacker gains credit card information on every user account they request it for.

## Parameter pollution

Cloudflare detects anomalies where one or more successful requests containing a value in an expected path, query string, header, or cookie have that value duplicated in an unexpected, similar location.

This behavior may be indicative of attackers trying to confuse the API's authorization system and bypass security controls.

Parameter pollution example

**Endpoint**: `GET /api/v1/orders/{orderId}`

* **Normal behavior**: `orderId` sent in a path variable like `GET /api/v1/orders/12345`
* **Attacker behavior**: `orderId` is also sent as a query parameter, triggering old, undocumented code that looks for orders in the query parameter and happens to lack an authorization check: `GET /api/v1/orders/12345?orderId=67890`
* **Result**: By passing in a fake order or an order that the attacker owns (`12345`), they are able to trigger the old, undocumented code and access an order that they do not own (`67890`)

## Process

API Shield searches for and highlights BOLA attacks on your APIs. Cloudflare learns visitor traffic patterns over time to know when API access to specific objects is likely a BOLA enumeration attack. We inform you what API endpoints are being targeted by automatically labeling them using the following [risk labels](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-labels/#risk-labels):

`cf-risk-bola-enumeration`: Automatically added when an endpoint experiences successful responses with drastic differences in the number of unique elements requested by different user sessions.

`cf-risk-bola-pollution`: Automatically added when an endpoint experiences successful responses where parameters are found in multiple places in the request, as opposed to what is expected from the API's schema.

If you see one of these labels on your API endpoints, check its authorization policy with your developer team to find any authorization bugs. Additionally, you can reach out to Cloudflare for a customized report about the behavior, including attacker identifiers that you can use to confirm attack reach and impact.

BOLA attack information can be found in your [Security Overview](#security-overview), [Security Analytics](#security-analytics), and [Endpoint details](#endpoint-details).

### Security Overview

If BOLA vulnerabilities have been detected on your endpoints, you can view a summary of the attack and suggestions to mitigate it via the Cloudflare dashboard.

1. In the Cloudflare dashboard, go to the **Security** page.  
[ Go to **Overview** ](https://dash.cloudflare.com/?to=/:account/:zone/security/overview)
2. Go to **API abuse** or **All suggestions**.
3. Depending on the type of attack, select **Review traffic from potential BOLA enumeration attack** or **Review traffic from potential parameter pollution attack** to view details of the attack and suggested actions.
4. Select **View all affected endpoints** or **View details** on a specific endpoint to review suspicious sessions in [Web Assets](#endpoint-details).

Cloudflare evaluates your session requests for both enumeration and parameter pollution attacks and provides you with a list of at-risk endpoints and the number of anomalous sessions where an attack was detected. You can follow the suggested actions to address your BOLA vulnerabilities and prevent future attacks against your endpoints.

Note

If the insight has been archived but attacks are still present, you can filter by **Show archived**.

### Security Analytics

You can view analytics of your zone's traffic profile and suspicious requests associated with enumeration or parameter pollution attacks in the Cloudflare dashboard.

[ Go to **Analytics** ](https://dash.cloudflare.com/?to=/:account/:zone/security/analytics) 

Filter requests depending on the type of attack detected in your zone, including the hashed session IDs found in the attack and the corresponding BOLA vulnerability risk label, to see an analysis of your request activity from the past seven days. This filter includes all traffic from suspected attacker sessions, so you can evaluate other actions that they are taking against your zone.

This does not filter by specific endpoints.

Review the top statistics and details of managed API endpoints, paths and values targeted by the attack, source IPs, source user agents, and source fingerprints.

Cloudflare recommends that you observe your traffic profile for any anomalies in its normal behavior.

### Endpoint details

You can expand the endpoint details in Web Assets to access information on suspicious sessions' activity on the endpoint, including both enumeration attack and parameter pollution attack details.

[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets) 

Under **Security overview**, select **View attack** to review affected sessions with its associated IP addresses and JA4 fingerprints.

You can export the `.csv` file containing all the IP addresses and JA4 fingerprints for all or only a specific session.

Note

The hashed session ID is used for privacy purposes and only as a unique identifier for a specific session. It cannot be un-hashed. It will not match your customer values in your application or database.

The details specify the parameter that was affected, the number of sessions involved in the attack, and how far their behavior deviated from baseline.

If unauthorized access to the parameter was obtained, consider the potential impact to your application, users, and data. As a best practice, consult with your application and API developers to confirm unauthorized access by reviewing your API origin logs for the IP address and JA4 fingerprint of the abusive sessions.

You can view attack data in [Security Analytics](#security-analytics).

[ Go to **Analytics** ](https://dash.cloudflare.com/?to=/:account/:zone/security/analytics) 

The managed endpoint will be automatically filtered in the request activity from the past seven days. You can also filter by suspicious IP addresses and fingerprints found in the attack details.

---

## Availability

Broken Object Level Authorization vulnerability detection is only available for Enterprise customers. If you are an Enterprise customer interested in this product, contact your account team.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/bola-vulnerability-detection/","name":"Broken Object Level Authorization vulnerability detection"}}]}
```

---

---
title: GraphQL malicious query protection
description: GraphQL is a query language for APIs. In addition to protecting RESTful APIs, Cloudflare can also protect GraphQL APIs.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/graphql-protection/index.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# GraphQL malicious query protection

GraphQL is a query language for APIs. In addition to protecting RESTful APIs, Cloudflare can also protect GraphQL APIs.

GraphQL malicious query protection scans your GraphQL traffic for queries that could overload your origin and result in a denial of service. You can build rules that limit the query depth and size of incoming GraphQL queries in order to block suspiciously large or complex queries.

## Availability

GraphQL malicious query protection is available for all API Shield customers. Enterprise customers who have not purchased API Shield can preview [API Shield as a non-contract service ↗](https://dash.cloudflare.com/?to=/:account/:zone/security/api-shield) in the Cloudflare dashboard or by contacting your account team.

## Limitations

Our initial release is limited to parsing GraphQL `POST` bodies smaller than 20 KB. This limit will be lifted in a future release. Additionally, we currently inspect only `POST` requests with `content-types` of `application/json` or `application/graphql` where the queries do not contain fragments or multiple operations. Parsing and rules are limited to paths ending in `/graphql`.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/graphql-protection/","name":"GraphQL malicious query protection"}}]}
```

---

---
title: Configure GraphQL malicious query protection via the API
description: Use the Cloudflare GraphQL API to gather data about your GraphQL API’s current usage and configure Cloudflare’s GraphQL malicious query protection to log or block malicious queries.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/graphql-protection/api.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Configure GraphQL malicious query protection via the API

Use the [Cloudflare GraphQL API](https://developers.cloudflare.com/analytics/graphql-api/getting-started/) to gather data about your GraphQL API’s current usage and configure Cloudflare’s GraphQL malicious query protection to log or block malicious queries.

## Introduction

Query size is defined as the number of terminal fields (leaves) in the query, whereas query depth is the deepest level at which a leaf is present. For example, the size of this query will be reported as `4 (terminalField[1-4] all contribute to this counter)`, and the depth will be reported as `3 (terminalField3 and terminalField4 are at depth level 3)`.

GraphQL query

```

{

  terminalField1

  nonTerminalField1(filter: 123) {

    terminalField2

    nonTerminalField2 {

      terminalField3

      terminalField4

    }

  }

}


```

## Gather GraphQL statistics

Using the new `apiGatewayGraphqlQueryAnalyticsGroups` node in the Cloudflare GraphQL API, you can retrieve `apiGatewayGraphqlQuerySize` and `apiGatewayGraphqlQueryDepth` dimensions.

GraphQL query

```

query ApiGatewayGraphqlQueryAnalytics(

  $zoneTag: string

  $start: Time

  $end: Time

) {

  viewer {

    zones(filter: { zoneTag: $zoneTag }) {

      apiGatewayGraphqlQueryAnalyticsGroups(

        limit: 100

        orderBy: [

          apiGatewayGraphqlQuerySize_DESC

          apiGatewayGraphqlQueryDepth_DESC

        ]

        filter: { datetime_geq: $start, datetime_leq: $end }

      ) {

        count

        dimensions {

          apiGatewayGraphqlQuerySize

          apiGatewayGraphqlQueryDepth

        }

      }

    }

  }

}


```

[Run in GraphQL API Explorer](https://graphql.cloudflare.com/explorer?query=I4VwpgTgngBAggBwJYHECGAXMB3NUURoIAWwANgIrjRwB2aZUGSAxgM4AUAUDDACQAvAPa0wAFTQBzAFww2GCElqSe-eWggZZYpAFswqvmFoATbXoMBKGAG9VANyQ5It1b2GjOAMyRksEWRsYD3EpWUERUMkYAF9rO15EmCJUTBw8AiJSSmooOgYmVjYCIRAETjckmDI9JC0YAEYABibKpKEIE0gAIShZAG02qpT0LFx8QhJyKkgoAGUkATAAfQARAFE5gGEhpJG08cypnNnVsAQMYjXNnarEgF1dmB8-SECYEzTmfWXJMGBwupNAAaD5fCzLMj-cLGEyxIbxJ4sUq0DBPEwWWhsJAiNiuO57ZCjdITLLTXILJZPXj7MYZSbZGbQM4XYhPGJDDlJLnwmJAA&variables=N4IgXg9gdgpgKgQwOYgFwgFoHkByBRAfQEkAREAGhAGcAXBAJxrRACYAGFgNgFo2AWXgGY4bNqgCs41G04YKIGFAAmzdl14C2wmRKky5AXyA)

With the above query, you will get the following response:

Response

```

{

  "data": {

    "viewer": {

      "zones": [

        {

          "apiGatewayGraphqlQueryAnalyticsGroups": [

            {

              "count": 10,

              "dimensions": {

                "apiGatewayGraphqlQueryDepth": 1,

                "apiGatewayGraphqlQuerySize": 11

              }

            },

            {

              "count": 10,

              "dimensions": {

                "apiGatewayGraphqlQueryDepth": 1,

                "apiGatewayGraphqlQuerySize": 2

              }

            }

          ]

        }

      ]

    }

  },

  "errors": null

}


```

In the response example, Cloudflare observed 10 requests with depth 1 and size 11, and 10 requests with depth 1 and size 2 in the selected timeframe.

## Analyze GraphQL statistics

You can use the response to compute percentiles across the attributes and set a threshold on what is allowed. For example, you can use a simple heuristic like `1.5 * p99` for query size or depth.

Here is a simple Python script that will report query size and depth p-levels given the GraphQL API response output above (as a JSON file):

Python script

```

#!/usr/bin/env python3


import json

import numpy as np

import argparse


parser = argparse.ArgumentParser()

parser.add_argument("--response", help="Path to the API JSON response file with the apiGatewayGraphqlQueryAnalyticsGroups node", required=True)

args = parser.parse_args()

with open(args.response) as f:

    query_sizes = np.array([], dtype=np.uint16)

    query_depths = np.array([], dtype=np.uint8)

    data = json.load(f)['data']['viewer']['zones'][0]['apiGatewayGraphqlQueryAnalyticsGroups']

    for datapoint in data:

        query_sizes = np.append(query_sizes, [datapoint['dimensions']['apiGatewayGraphqlQuerySize']] * datapoint['count'])

        query_depths = np.append(query_depths, [datapoint['dimensions']['apiGatewayGraphqlQueryDepth']] * datapoint['count'])


    quantiles = [0.99, 0.95, 0.75, 0.5]

    print('\n'.join([f"Query size {int(q * 100)}th percentile is {v}" for q, v in zip(quantiles, np.quantile(query_sizes, quantiles))]))

    print('\n'.join([f"Query depth {int(q * 100)}th percentile is {v}" for q, v in zip(quantiles, np.quantile(query_depths, quantiles))]))


```

With the above query, you will get the following output:

```

./calculator.py --response=response.json

Query size 99th percentile is 11.0

Query size 95th percentile is 11.0

Query size 75th percentile is 11.0

Query size 50th percentile is 6.5

Query depth 99th percentile is 1.0

Query depth 95th percentile is 1.0

Query depth 75th percentile is 1.0

Query depth 50th percentile is 1.0


```

## Set limits on incoming GraphQL queries

API Shield customers now have three new fields available in custom rules:

* `cf.api_gateway.graphql.query_size` describes the size of a GraphQL query.
* `cf.api_gateway.graphql.query_depth` describes the depth of a GraphQL query.
* `cf.api_gateway.graphql.parsed_successfully` describes whether Cloudflare was able to parse the query. Presently, we run best-effort parsing, meaning we might not be able to parse some valid queries. This means that you must use a `and cf.api_gateway.graphql.parsed_successfully` filter in your custom rules when deploying GraphQL security rules.

For example, you can deploy the following rule via the API or the dashboard to block queries that are deeply nested and ask for over 30 fields.

```

(cf.api_gateway.graphql.query_size > 30 and cf.api_gateway.graphql.query_depth > 7 and cf.api_gateway.graphql.parsed_successfully)


```

Note

You are not able to configure which endpoints the GraphQL parsing runs on. Requests are parsed if they are targeting a path ending in `/graphql`.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/graphql-protection/","name":"GraphQL malicious query protection"}},{"@type":"ListItem","position":5,"item":{"@id":"/api-shield/security/graphql-protection/api/","name":"Configure GraphQL malicious query protection via the API"}}]}
```

---

---
title: JSON Web Tokens validation
description: JSON web tokens (JWT) are often used as part of an authentication component on many web applications today. Since JWTs are crucial to identifying users and their access, ensuring the token’s integrity is important.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/jwt-validation/index.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# JSON Web Tokens validation

JSON web tokens (JWT) are often used as part of an authentication component on many web applications today. Since JWTs are crucial to identifying users and their access, ensuring the token’s integrity is important.

API Shield’s JWT validation stops JWT replay attacks and JWT tampering by cryptographically verifying incoming JWTs before they are passed to your API origin. JWT validation will also stop requests with expired tokens or tokens that are not yet valid.

## Process

Endpoints must be added to [Endpoint Management](https://developers.cloudflare.com/api-shield/management-and-monitoring/) for JWT validation to protect them.

A JWT validation configuration consists of creating a token validation configuration by adding your JWT signer's public JSON Web Key Set (JWKS) and a JWT validation rule by specifying which hostnames and endpoints should be included for validation.

### Add a token validation configuration

* [  New dashboard ](#tab-panel-3160)
* [ Old dashboard ](#tab-panel-3161)

1. In the Cloudflare dashboard, go to the **Security Settings** page.  
[ Go to **Settings** ](https://dash.cloudflare.com/?to=/:account/:zone/security/settings)
2. Filter by **API abuse**.
3. On **Token configurations**, select **Configure tokens**.
4. Add a name for your configuration.
5. Choose where Cloudflare can locate the JWT for this configuration on incoming requests, such as a header or cookie and its name.
6. Copy and paste your JWT issuer's public key(s) (JWKS).

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/login), and select your account and domain.
2. Go to **Security** \> **API Shield** \> **Settings**.
3. Under **JSON Web Token Settings**, select **Add configuration**.
4. Add a name for your configuration.
5. Choose where Cloudflare can locate the JWT for this configuration on incoming requests, such as a header or cookie and its name.
6. Copy and paste your JWT issuer's public key(s) (JWKS).

Each JWT issuer typically publishes public keys (JWKS) for verification at a known URL on the Internet. If you do not know where to get them, contact your identity administrator.

To automatically keep your JWKS up to date when your identity provider refreshes them, you can use a Worker. Refer to [Configure Workers to automatically update keys](https://developers.cloudflare.com/api-shield/security/jwt-validation/jwt-worker/) to learn more about setting up the Worker.

### Add a JWT validation rule

* [  New dashboard ](#tab-panel-3162)
* [ Old dashboard ](#tab-panel-3163)

1. In the Cloudflare dashboard, go to the **Security rules** page.  
[ Go to **Security rules** ](https://dash.cloudflare.com/?to=/:account/:zone/security/security-rules)
2. On API JWT validation rules, select **Create rule**.
3. Add a name for your rule.
4. Select a hostname to protect requests with saved endpoints using the rule.
5. Deselect any endpoints that you want JWT validation to ignore (for example, an endpoint used to generate a JWT).
6. Select the token validation configuration that corresponds to the incoming requests.
7. Choose whether to strictly enforce token presence on these endpoints.  
   * You may not expect 100% of clients to send in JWTs with their requests. If this is the case, choose _Ignore_. JWT validation will still validate JWTs that are present.  
   * You may otherwise expect all requests to the selected hostname and endpoints to contain JWTs. If this is the case, choose _Mark as non-compliant_.
8. Choose an action to take for non-compliant requests. For example, JWTs that do not pass validation (expired, tampered with, or bad signature tokens) or requests with missing JWTs when _Mark as non-compliant_ is selected in the previous step.
9. Select **Save**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/login), and select your account and domain.
2. Go to **Security** \> **API Shield** \> **API Rules**.
3. Add a name for your rule.
4. Select a hostname to protect requests with saved endpoints using the rule.
5. Deselect any endpoints that you want JWT validation to ignore (for example, an endpoint used to generate a JWT).
6. Select the token validation configuration that corresponds to the incoming requests.
7. Choose whether to strictly enforce token presence on these endpoints.  
   * You may not expect 100% of clients to send in JWTs with their requests. If this is the case, choose _Ignore_. JWT validation will still validate JWTs that are present.  
   * You may otherwise expect all requests to the selected hostname and endpoints to contain JWTs. If this is the case, choose _Mark as non-compliant_.
8. Choose an action to take for non-compliant requests. For example, JWTs that do not pass validation (expired, tampered with, or bad signature tokens) or requests with missing JWTs when _Mark as non-compliant_ is selected in the previous step.
9. Select **Save**.

Note

Token configuration rules will automatically apply to new endpoints added to Endpoint Management if those endpoints also match the rule.

---

## Special cases

### Validate two JWTs with different identity providers on a single request

If you expect that two different JWTs should be present in a request and you want to validate both, you must create two different token configurations. When selecting the two configurations in your validation rule, select _Validate all configurations_ under **Validation behavior for multiple configurations**.

### Support a migration from one identity provider to another

If you expect to migrate between two different identity providers, you must create two different token configurations and two different validation rules, each corresponding to its own configuration. With this setup, you can change the action for different validation rules depending on the state of your migration.

### JSON Web Tokens with the `Bearer` prefix

API Shield will verify JSON Web Tokens regardless of whether or not they have the `Bearer` prefix.

### Rate limit by user (JWT claim)

You can rate limit requests based on any claim inside of a JSON Web Token (JWT), such as:

* Registered claims like `aud` or `sub`
* Custom claims like `userEmail`, including nested custom claims like `user.email`

Rate limiting based on JWT claim values will only work on valid JSON Web Tokens. If you do not block invalid JSON Web Tokens on your path, the [JWT claims will all be counted and possibly blocked](https://developers.cloudflare.com/waf/rate-limiting-rules/parameters/#missing-field-versus-empty-value) if high traffic is detected in the Point of Presence (PoP).

You must also count the JWT claim that uniquely identifies the user. If you select a claim that is the same for many of your users, their rate limits will all be counted together.

### Rate limit by user tier

If you offer multiple tiers on your website or application and you want to enforce rate limiting based on the tiers, such as:

* If `"aud": "free-tier"`, rate limit to five requests per minute.
* If `"aud": "premium-tier"`, rate limit to 50 requests per minute.

You can follow the rate limiting rule example below:

Example rule expression

```

(http.request.method eq "GET" and

http.host eq "<YOUR_DOMAIN>" and

http.request.uri.path matches "</EXAMPLE_PATH>" and

lookup_json_string(http.request.jwt.claims["<JWT_TOKEN_CONFIGURATION_ID>"][0], "aud") eq "free-tier"


```

### Ignore `OPTIONS` pre-flight CORS requests

Due to cross-origin resource sharing (CORS) security, web browsers will send "pre-flight" requests using the `OPTIONS` verb to API endpoints before sending a `GET` (or other verb) request. By definition, `OPTIONS` requests do not include headers or cookies and are anonymous.

If you expect web browsers to be valid clients of your API, and to prevent blocking `OPTIONS` requests from those browsers, Cloudflare recommends adding `or http.request.method eq "OPTIONS"` to your JWT validation rules.

---

## Availability

JWT validation is available for all API Shield customers. Enterprise customers who have not purchased API Shield can preview [API Shield as a non-contract service ↗](https://dash.cloudflare.com/?to=/:account/:zone/security/api-shield) in the Cloudflare dashboard or by contacting your account team.

---

## Limitations

Currently, the following known limitations exist:

1. JWT validation only operates on JWTs sent in client request headers or cookies. If your clients send in JWTs in a `POST` body, direct that feedback to your account team.
2. JWT validation only operates for endpoints (host, method, and path) added to Endpoint Management. You can add all of your endpoints to endpoint management through [API Discovery](https://developers.cloudflare.com/api-shield/management-and-monitoring/#add-endpoints-from-api-discovery), [Schema validation](https://developers.cloudflare.com/api-shield/management-and-monitoring/#add-endpoints-from-schema-validation), [manually via the Cloudflare dashboard](https://developers.cloudflare.com/api-shield/management-and-monitoring/#add-endpoints-manually), or via the [API](https://developers.cloudflare.com/api/resources/api%5Fgateway/subresources/operations/methods/create/).

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/jwt-validation/","name":"JSON Web Tokens validation"}}]}
```

---

---
title: Configure JWT validation via the API
description: Use the Cloudflare API to configure JWT validation, which requires token configurations and token validation rules.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/jwt-validation/api.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Configure JWT validation via the API

Use the Cloudflare API to configure [JWT validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/), which requires token configurations and token validation rules.

## Token configurations

A token configuration defines a JSON Web Key Set (JWKs), which is used to validate JSON Web Tokens (JWTs) sent by clients and information on where these JWTs are sent in the request.

Note

A zone may have up to four token configurations.

Token configurations require the following information:

| Field name     | Description                                                                                                                                                 | Example                                                                                                             | Notes                                             |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
| title          | A human-readable name for the configuration that allows to quickly identify the purpose of the configuration.                                               | Production JWT configuration                                                                                        | Limited to 50 characters.                         |
| description    | A human-readable description that gives more details than title which serves as a means to allow customers to better document the use of the configuration. | This configuration is used for all endpoints in endpoint management and checks the JWT in the authorization header. | Limited to 500 characters.                        |
| token\_sources | A list of possible locations where then JWT can be found on the request.                                                                                    | http.request.headers\[\\"authorization\\"\]\[0\] http.request.cookies\[\\"Authorization\\"\]\[0\]                   | Refer to the [information](#token-sources) below. |
| token\_type    | This specifies the type of token to validate.                                                                                                               | jwt                                                                                                                 | Only jwt is currently supported.                  |
| credentials    | This describes the cryptographic public keys that should be used to validate JWTs. This field must be a JSON web key.                                       | Refer to the example below.                                                                                         | Refer to the [information](#credentials) below.   |

### Token sources

Each item must be a Ruleset Engine expression that resolves to a string.

Currently supported fields are `http.request.headers` and `http.request.cookies`.

You can set up to four token sources. If a request has more than one of these fields set, only one will be used. Leading `Bearer: ` strings in request tokens are automatically ignored.

Refer to the [Ruleset Engine documentation](https://developers.cloudflare.com/ruleset-engine/rules-language/fields) for details on working with Ruleset Engine fields.

### Credentials

API Shield supports credentials of type `RS256`, `RS384`, `RS512`, `PS256`, `PS384`, `PS512`, `ES256`, and `ES384`. RSA keys must be at least 2048-bit. Each JSON web key must have a “KID” which must be present in the JWT's header as well to allow API Shield to match them.

We allow up to 4 different keys in order to aid in key rollover.

Cloudflare will remove any fields that are unnecessary from each key and will drop keys that we do not support.

It is highly recommended to validate the output of the API call to check that the resulting keys appear as intended.

## Token configuration JSON object

The example below shows a JSON object with all of the information necessary to create a token configuration using the Cloudflare API. If you would like to create JWKs for testing, refer to [mkjwk JSON Web Key Generator ↗](https://mkjwk.org/).

Example

```

{

    "title": "Production JWT configuration",

    "description": "This configuration checks the JWT in the authorization header or cookie.",

    "token_sources": [

        "http.request.headers[\"authorization\"][0]",

        "http.request.cookies[\"Authorization\"][0]"

    ],

    "token_type": "jwt",

    "credentials": {

        "keys": [

            {

                "kty": "EC",

                "use": "sig",

                "crv": "P-256",

                "kid": "93UrzmNu1mqXs5cZcvCPkTlMHB2Jya30vSTkiBb0vhU",

                "x": "QG3VFVwUX4IatQvBy7sqBvvmticCZ-eX5-nbtGKBOfI",

                "y": "A3PXCshn7XcG7Ivvd2K_DerW4LHAlIVKdqhrUnczTD0",

                "alg": "ES256"

            }

        ]

    }

}


```

## Create a token configuration using the Cloudflare API

Use cURL or any other API client tool to send the new configuration to Cloudflare’s API to enable JWT validation. Make sure to replace `{zone_id}` with the relevant zone ID and add your [authentication credentials](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/) header.

Example using cURL

```

curl "https://api.cloudflare.com/client/v4/zones/{zone_id}/token_validation/config" \

--header 'Content-Type: application/json' \

--data '{

    "title": "Production JWT configuration",

    "description": "This configuration checks the JWT in the authorization header or cookie.",

    "token_sources": [

        "http.request.headers[\"authorization\"][0]",

        "http.request.cookies[\"Authorization\"][0]"

    ],

    "token_type": "jwt",

    "credentials": {

        "keys": [

            {

                "kty": "EC",

                "use": "sig",

                "crv": "P-256",

                "kid": "93UrzmNu1mqXs5cZcvCPkTlMHB2Jya30vSTkiBb0vhU",

                "x": "QG3VFVwUX4IatQvBy7sqBvvmticCZ-eX5-nbtGKBOfI",

                "y": "A3PXCshn7XcG7Ivvd2K_DerW4LHAlIVKdqhrUnczTD0",

                "alg": "ES256"

            }

        ]

    }

}'


```

The response will be in a Cloudflare `v4` response envelope and the result contains the created configuration. Note the returned ID, as it will be used to reference the token configuration when creating token validation rules using the API.

Example response

```

{

    "result": {

        "id": "d5902294-00c3-4aed-b517-57e752e9cd58",

        "token_type": "JWT",

        "title": "Production JWT configuration",

        "description": "This configuration checks the JWT in the authorization header or cookie.",

        "token_sources": [

            "http.request.headers[\"authorization\"][0]",

            "http.request.cookies[\"Authorization\"][0]"

        ],

        "credentials": {

            "keys": [

                {

                    "x": "QG3VFVwUX4IatQvBy7sqBvvmticCZ-eX5-nbtGKBOfI",

                    "y": "A3PXCshn7XcG7Ivvd2K_DerW4LHAlIVKdqhrUnczTD0",

                    "alg": "ES256",

                    "crv": "P-256",

                    "kid": "93UrzmNu1mqXs5cZcvCPkTlMHB2Jya30vSTkiBb0vhU",

                    "kty": "EC"

                }

            ]

        },

        "created_at": "2023-11-08T16:45:17.236841Z",

        "last_updated": "2023-11-08T16:45:17.236841Z"

    },

    "success": true,

    "errors": [],

    "messages": []

}


```

## Token validation rules

Token validation rules allow you to enforce a security policy using existing token configurations.

Token validation rules can be configured using the Cloudflare API or [dashboard](https://developers.cloudflare.com/api-shield/security/jwt-validation/#add-a-jwt-validation-rule).

| Field name  | Description                                                                               | Example                                                                      | Notes                                                                                                                                               |
| ----------- | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| title       | A human-readable name allowing you to quickly identify it.                                | JWT validation on v1 and v2.example.com                                      | Limited to 50 characters.                                                                                                                           |
| description | A human-readable description that gives more details than title and helps to document it. | Log requests without a valid authorization header.                           | Limited to 500 characters.                                                                                                                          |
| action      | The Firewall Action taken on requests that do not meet expression.                        | log                                                                          | Possible: log or block                                                                                                                              |
| enabled     | Enable or disable the rule.                                                               | true                                                                         | Possible: true or false                                                                                                                             |
| expression  | The rule's security policy.                                                               | is\_jwt\_valid ("00170473-ec24-410e-968a-9905cf0a7d03")                      | Make sure to escape any quotes when creating rules using the Cloudflare API.  Refer to [Define a security policy](#define-a-security-policy) below. |
| selector    | Configure what operations are covered by this rule.                                       | Refer to [Applying a rule to operations](#apply-a-rule-to-operations) below. |                                                                                                                                                     |

### Selectors

Selectors control the scope of your token validation rule.

If you only need JWT validation on specific hostnames or subdomains of your apex domain, use the hostname in a selector to include it in the JWT validation rule.

If you need to exclude endpoints from JWT validation that never have valid JWTs used with them (by design), such as a path and method used to establish a valid JWT in the first place, you must use the endpoint’s operation ID to exclude the endpoint in a selector.

To find the operation ID, refer to [Endpoint Management](https://developers.cloudflare.com/api-shield/management-and-monitoring/) or use the [Cloudflare API](https://developers.cloudflare.com/api/resources/api%5Fgateway/subresources/operations/methods/list/).

## Define a security policy

Note

A request must also match an operation covered by this rule to trigger an action.

Refer to [Apply a rule to operations](#apply-a-rule-to-operations) for more information.

A token validation rule's expression defines a security policy that a request must meet.

For example, the expression `is_jwt_valid("51231d16-01f1-48e3-93f8-91c99e81288e") or is_jwt_valid("51231d16-01f1-48e3-93f8-91c99e81288e")` will trigger if an incoming request does not have at least one valid authentication token.

These expressions are similar to [expressions used in Ruleset Engine](https://developers.cloudflare.com/ruleset-engine/rules-language/), with a few key differences:

* The token validation rule actions trigger if the expression evaluates `false`, as opposed to Ruleset expressions.
* The token validation rules can use dedicated functions that reference token configurations.

Operators such as `or`, `and`, `eq`, and more are usable in expressions in the same way as in expressions used in Ruleset Engine.

The following functions can be used to interact with JWT Tokens on a request:

| Function                                               | Description                                                                                                      | Notes                                                                                                                                        |
| ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| is\_jwt\_valid(token\_configuration\_id String) bool   | True if the request has a valid token according to the token configuration with the ID token\_configuration\_id. | token\_configuration\_id must be the ID of an existing token configuration. This will return false if the token is missing from the request. |
| is\_jwt\_present(token\_configuration\_id String) bool | True if the request has a token as configured in the token configuration with the ID token\_configuration\_id.   | token\_configuration\_id must be the ID of an existing token configuration.                                                                  |

### Common use cases

Refer to the following example use cases to understand which security policy to use. For most use cases, Cloudflare recommends requiring a valid token across your API and excluding any paths that are used to establish or refresh tokens using selectors.

#### Require a token

The `is_jwt_present("51231d16-01f1-48e3-93f8-91c99e81288e")` expression will trigger an action if a request is missing a JWT.

It can be combined with a `log` action in the token validation rule to log requests that are missing an authentication header.

#### Require a valid token

The `is_jwt_valid("51231d16-01f1-48e3-93f8-91c99e81288e")` expression will trigger an action if a request does not have a valid JWT.

It can be combined with a `block` action in the token validation rule to block requests with no or invalid credentials.

#### Require at least one of two possible tokens

The `is_jwt_valid("51231d16-01f1-48e3-93f8-91c99e81288e") or is_jwt_valid("fddfc39e-3686-4683-ab23-bf917da6bb43")` expressions will trigger an action if a request does not have at least one valid token.

This can occur if you need to split JWKs into multiple token configurations.

#### Require a valid token but ignore requests without a token

The `is_jwt_valid("51231d16-01f1-48e3-93f8-91c99e81288e") or not is_jwt_present("51231d16-01f1-48e3-93f8-91c99e81288e")` expressions will trigger an action if a request has an invalid token, ignoring requests with no tokens at all.

## Apply a rule to operations

Only one token validation rule can apply to an operation. If an operation is covered by multiple rules, then the rule with highest precedence will take effect.

You can configure which operations JWT validation is enforced on using the `selector` field.

Note

Selectors will also apply to new operations. New operations that match an existing selector will automatically be covered by that token validation rule.

For example, the following selector will apply a rule to all operations in `v1.example.com` and `v2.example.com`, except for two operations on these hosts:

Selector example

```

{

    "include": [

        {

            "host": [

                "v1.example.com",

                "v2.example.com"

            ]

        }

    ],

    "exclude": [

        {

            "operation_ids": [

                "f9c5615e-fe15-48ce-bec6-cfc1946f1bec", // POST v1.example.com/login

                "56828eae-035a-4396-ba07-51c66d680a04"  // POST v2.example.com/login

            ]

        }

    ]

}


```

Operations can be included at a host level and ignored on a per-operation basis.

You can use the `POST /zones/{zone_id}/token_validation/rules/preview` endpoint to see the operations covered by this rule:

Example using cURL

```

curl --request PUT \

'https://api.cloudflare.com/client/v4/zones/{zone_id}/token_validation/rules/preview' \

--header 'Content-Type: application/json' \

--data '{

    "include": [

        {

            "host": [

                "v1.example.com",

                "v2.example.com"

            ]

        }

    ],

    "exclude": [

        {

            "operation_ids": [

                "f9c5615e-fe15-48ce-bec6-cfc1946f1bec", // POST v1.example.com/login

                "56828eae-035a-4396-ba07-51c66d680a04"  // POST v2.example.com/login

            ]

        }

    ]

}'


```

The response will include all operations on a zone with an additional `state` field.

The `state` field can be `ignored`, `excluded`, or `included`. Included operations will match the hostname selectors you specified. Excluded operations will match the operation IDs you specified in the selector. Ignored operations are those that do not match anything specified in the selector.

Result

```

{

    "result": {

        "operations": [

            {

                "operation_id": "ed15fcb6-5a73-41cd-91af-8c61e5bb1cdb",

                "method": "GET",

                "host": "example.com",

                "endpoint": "/api/accounts/{var1}",

                "last_updated": "2023-05-24T14:54:34.806506Z",

                "state": "ignored"

            },

            {

                "operation_id": "e7a582cd-3cfb-4061-ab5b-722e6e42f545",

                "method": "GET",

                "host": "v1.example.com",

                "endpoint": "/api/accounts/{var1}",

                "last_updated": "2023-05-24T14:54:34.806506Z",

                "state": "included"

            },

            {

                "operation_id": "ddd5df5a-795c-40ce-b38c-38e9d7ef9ae8",

                "method": "GET",

                "host": "v2.example.com",

                "endpoint": "/api/accounts/{var1}",

                "last_updated": "2023-05-24T14:54:34.806506Z",

                "state": "included"

            },

            {

                "operation_id": "4d20befb-0120-45d5-9b29-5835fd41b44e",

                "method": "GET",

                "host": "v3.example.com",

                "endpoint": "/api/accounts/{var1}",

                "last_updated": "2023-05-24T14:54:34.806506Z",

                "state": "ignored"

            },

            {

                "operation_id": "f9c5615e-fe15-48ce-bec6-cfc1946f1bec",

                "method": "POST",

                "host": "v1.example.com",

                "endpoint": "/login",

                "last_updated": "2023-05-24T14:54:34.806506Z",

                "state": "excluded"

            },

            {

                "operation_id": "56828eae-035a-4396-ba07-51c66d680a04",

                "method": "POST",

                "host": "v2.example.com",

                "endpoint": "/login",

                "last_updated": "2023-05-24T14:54:34.806506Z",

                "state": "excluded"

            },

            {

                "operation_id": "cf86874c-8d0c-4337-ae14-4e2459b541ac",

                "method": "GET",

                "host": "v3.example.com",

                "endpoint": "login",

                "last_updated": "2023-05-24T14:54:34.806506Z",

                "state": "ignored"

            }

        ],

        "total": 7,

        "included": 2,

        "excluded": 2,

        "ignored": 3,

        "selected_hosts": [

            "v1.example.com",

            "v2.example.com"

        ],

        "available_hosts": [

            "example.com",

            "v1.example.com",

            "v1.example.com",

            "v3.example.com"

        ]

    },

    "success": true,

    "errors": [],

    "messages": [],

    "result_info": {

        "page": 1,

        "per_page": 20,

        "count": 20,

        "total_count": 1631

    }

}


```

Operations with a `included` state will be covered by the token validation rule. The response also shows the hostnames of included operations in `result.selected_hosts` and shows all hostnames used by all zone operations in `result.available_hosts`.

You can also send an empty object in the request body:

Example using cURL

```

curl --request PUT \

'https://api.cloudflare.com/client/v4/zones/{zone_id}/token_validation/rules/preview' \

--header 'Content-Type: application/json' \

--data '{ }'


```

The response will show all zone operations and all possible hosts, which you can use to build your own selector.

## Token validation rule JSON object

The example below shows a JSON object with all the necessary information to create a token validation rule using the Cloudflare API.

Replace any token configurations IDs and operation IDs with the IDs that exist in your zone.

Token Validation Rule JSON example

```

[

    {

        "title": "JWT Validation on v1 and v2.example.com",

        "description": "Log requests without a valid authorization header.",

        "action": "log",

        "enabled": true,

        "expression": "is_jwt_valid(\"00170473-ec24-410e-968a-9905cf0a7d03\")",

        "selector": {

            "include": [

                {

                    "host": [

                        "v1.example.com",

                        "v2.example.com"

                    ]

                }

            ],

            "exclude": [

                {

                    "operation_ids": [

                        "f9c5615e-fe15-48ce-bec6-cfc1946f1bec",

                        "56828eae-035a-4396-ba07-51c66d680a04"

                    ]

                }

            ]

        }

    }

]


```

## Create a token Validation rule using the Cloudflare API

Use cURL or any other API client tool to send the new configuration to Cloudflare’s API to enable JWT validation. Make sure to replace `{zone_id}` with the relevant zone ID and add your [authentication credentials](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/) header.

Replace any token configurations IDs and operation IDs with the IDs that exist in your zone.

A single request can create multiple rules. To do so, pass multiple rule objects in the JSON array of the request body.

Example using cURL

```

curl "https://api.cloudflare.com/client/v4/zones/{zone_id}/token_validation/rules/bulk" \

--header 'Content-Type: application/json' \

--data '[

    {

        "title": "JWT Validation on v1 and v2.example.com",

        "description": "Log requests without a valid authorization header.",

        "action": "log",

        "enabled": true,

        "expression": "is_jwt_valid(\"00170473-ec24-410e-968a-9905cf0a7d03\")",

        "selector": {

            "include": [

                {

                    "host": [

                        "v1.example.com",

                        "v2.example.com"

                    ]

                }

            ],

            "exclude": [

                {

                    "operation_ids": [

                        "f9c5615e-fe15-48ce-bec6-cfc1946f1bec",

                        "56828eae-035a-4396-ba07-51c66d680a04"

                    ]

                }

            ]

        }

    }

]'


```

The response will be in a Cloudflare `v4` response envelope and the result contains the created rules. Note the returned ID for each rule, which can be used to edit or delete an existing rule.

Result

```

{

    "result": [

        {

            "id": "5ec7c417-6964-4b24-b82c-a23a7ec8f90c",

            "title": "JWT Validation on v1 and v2.example.com",

            "description": "Log requests without a valid authorization header.",

            "action": "log",

            "enabled": true,

            "expression": "is_jwt_valid(\"00170473-ec24-410e-968a-9905cf0a7d03\")",

            "selector": {

                "include": [

                    {

                        "host": [

                            "v1.example.com",

                            "v2.example.com"

                        ]

                    }

                ],

                "exclude": [

                    {

                        "operation_ids": [

                            "f9c5615e-fe15-48ce-bec6-cfc1946f1bec",

                            "56828eae-035a-4396-ba07-51c66d680a04"

                        ]

                    }

                ]

            },

            "created_at": "2023-10-18T12:08:09.575388Z",

            "last_updated": "2023-10-18T12:08:09.575388Z",

            "modified_by": "user@cloudflare.com"

        }

    ],

    "success": true,

    "errors": [],

    "messages": []

}


```

## Maintenance

### Update token configuration

It is best practice to rotate keys after some time. To support updating the keys, Cloudflare allows up to four keys per configuration. This allows you to add a second, new key to an already existing key. You can start issuing JWTs with the new key only and remove the old key after some time. Additionally, this feature allows the deployment of testing or development keys next to production keys.

The input to updating the keys is the same as when creating a configuration where you supplied the initial keys using the credentials key and needs to be a JWK.

Note

Cloudflare will remove any fields that are unnecessary from each key and will drop keys that we do not support.

It is highly recommended to validate the output of the API call to check that the resulting keys appear as intended.

Use the `PUT` command to update keys.

Example using cURL

```

curl --request PUT \

'https://api.cloudflare.com/client/v4/zones/{zone_id}/token_validation/config/{config_id}/credentials' \

--header 'Content-Type: application/json' \

--data '{

    "keys": [

        {

            "kty": "EC",

            "use": "sig",

            "kid": "test",

            "x": "-0LNzBheJPn-Zy6JmanTIUX7xc3jgqU714IQY0oU6mw",

            "y": "KONxBybUcRsJQmtu17jMAHsILSw009AuU3ulfUGv3FI",

            "alg": "ES256"

        },

        {

            "kty": "EC",

            "crv": "P-256",

            "kid": "test-2",

            "x": "iIbPRbOeLzjGPvv7iwmzCOTU03R0xDqbenp2D6GUcWo",

            "y": "tDkEh95PnfWwIXciCtdBBVA7wfghx_egmZ1Zcvu2lWw",

            "alg": "ES256"

        }

    ]

}'


```

Make sure to replace `{zone_id}` with the relevant zone ID and add your [authentication credentials](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/) header.

### Update token validation rules

Token validation rules can be updated with a `PATCH` request. A single `PATCH` request can update multiple rules.

A `PATCH` request is specified as a JSON array in the request body. Each item in that array contains updates to a single rule, defined by `id`.

The following example updates one rule and disables another:

Example using cURL

```

curl --request PATCH \

"https://api.cloudflare.com/client/v4/zones/{zone_id}/token_validation/rules/bulk"  \

--header "Content-Type: application/json" \

--data '[

    {

        "id": "714d3dd0-cc59-4911-862f-8a27e22353cc",

        "action": "log",

        "title": "updated title"

    },

    {

        "id": "7124f9bc-d6b5-430d-b488-b6bc2892f2fb",

        "enabled": false

    }

]'


```

Rules can be reordered by setting a position field in the `PATCH` body.

This example places rule `714d3dd0-cc59-4911-862f-8a27e22353cc` after rule `7124f9bc-d6b5-430d-b488-b6bc2892f2fb`:

Example using cURL

```

curl --request PATCH \

"https://api.cloudflare.com/client/v4/zones/{zone_id}/token_validation/rules/bulk" \

--header 'Content-Type: application/json' \

--data '[

    {

        "id": "714d3dd0-cc59-4911-862f-8a27e22353cc",

        "position": {

            "after": "7124f9bc-d6b5-430d-b488-b6bc2892f2fb"

        }

    }

]'


```

This example places rule `714d3dd0-cc59-4911-862f-8a27e22353cc` before rule `7124f9bc-d6b5-430d-b488-b6bc2892f2fb`:

Example using cURL

```

curl --request PATCH \

"https://api.cloudflare.com/client/v4/zones/{zone_id}/token_validation/rules/bulk" \

--header 'Content-Type: application/json' \

--data '[

    {

        "id": "714d3dd0-cc59-4911-862f-8a27e22353cc",

        "position": {

            "before": "7124f9bc-d6b5-430d-b488-b6bc2892f2fb"

        }

    }

]'


```

## Perform JWT validation

Here is an overview of how JWT validation processes incoming requests:

1. We extract the JWT in accordance with the configuration from the incoming request.
2. We decode the JWT and look for the JWTs header KID claim.
3. We use the KID and ALG claim to find the correct keys in the list of supplied keys.

Note

The absence of matching keys directly marks the JWT as invalid.

1. We validate the authenticity of the JWT by checking the signature using the selected key.
2. Should the JWT contain an EXP claim (expiration time), we validate that the JWT is not expired.

Note

We allow a mismatch of up to 60 seconds to account for clock drifts between the Cloudflare network and the JWT issuer. A token may still be regarded as valid one minute after it was supposed to expire when both clocks are perfectly in sync.

1. Should the JWT contain a NBF claim (not before time), we validate that the JWT is already valid.

Note

The same accuracy applies as for EXP claims. As such, a token may be already regarded as valid one minute before its NBF claim in case of perfect synchronization between issuer and validator.

1. The final validation result and whether a token was present at all is made available to the WAF which applies the policy’s configured action (`log`/`block`).
2. Security Analytics events in the Cloudflare dashboard for the `API Shield - Token Validation` service will explain violation reasons in the `Token validation violations` section of the event.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/jwt-validation/","name":"JSON Web Tokens validation"}},{"@type":"ListItem","position":5,"item":{"@id":"/api-shield/security/jwt-validation/api/","name":"Configure JWT validation via the API"}}]}
```

---

---
title: Configure the Worker
description: Use a Worker to automatically keep your identity provider’s latest public key in the JWT validation configuration.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/jwt-validation/jwt-worker.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Configure the Worker

Use a Worker to automatically keep your identity provider’s latest public key in the JWT validation configuration.

## Prerequisites

* Find your zone ID. You can locate this ID in your zone overview in the [Cloudflare dashboard ↗](https://dash.cloudflare.com/).
* Find your identity provider’s JSON Web Key Set (JWKs) URL. Identity providers commonly list it in Open Authorization (OAuth) settings.
* Create a [token validation configuration](https://developers.cloudflare.com/api-shield/security/jwt-validation/#add-a-token-validation-configuration).
* [Create a new API token ↗](https://dash.cloudflare.com/profile/api-tokens) with the API Gateway `Write` permission.

## Process

You must manually query the JWKs endpoint to ensure the JWKs exists in the expected location and format. Then, create a Worker to automate updating of the JWKs and a [Worker Secret](https://developers.cloudflare.com/workers/configuration/secrets/#via-the-dashboard) to house the API key used for updating API Shield settings. You can then schedule the Worker to automatically update the JWKs.

### Manually query the JWKs endpoint

Find your Identity Provider’s URL and fetch the keys using `curl` and `jq`. Your URL may return more than just the issuer’s keys, so Cloudflare recommends using `jq` to filter the response to only return the keys. You must update the provided Worker sample code if your JWKs do not have a `keys` object.

Note

The keys listed below are for example purposes only and must not be used in your production environment, as they will never match the keys used by your identity provider to sign JWTs.

Query the JWKs endpoint

```

curl https://<your-team-name>.cloudflareaccess.com/cdn-cgi/access/certs -s | jq .keys


```

```

[

  {

    "kid": "ca96ae653935dbfb49b4e19de600cc5f9d5c63e3ac2dbee406ed4bf0ae100cce",

    "kty": "RSA",

    "alg": "RS256",

    "use": "sig",

    "e": "AQAB",

    "n": "9dG9Ph4ffncvEA9FO9pVMfJ1dh_5mtuyiIE4ap9ScrufVPq1I34St_dhcFavKiytK7Id7gTlgQgaouoJ0I5OJ_bytgX-B7oOUQHO-nJOAMycORXN8ZNaMBPKg9nBLL_BFY0YX5HggqrkXkZjJ--R4JpB30ENS8A6hxmEJ__yGMZTE2LHZoiYj9iyGNu3s3JflAoRlmziI8LsFXwyFAJUWRZq4SkSfyrRJ89pXPxIqBn9uYBtnxWzUpWG3xKZu0JAbi9YiwFCJrSe_CarvpARoWsOldtrty5yT1yJ1PZlImlF-yuEwjOoZxeib4WSidABZH0O3pbDACo8MfxR5rghHQ"

  },

  {

    "kid": "1e590a6dcd60e3e2306c21eca19144c59d591531267a3ebde8d521f40894329d",

    "kty": "RSA",

    "alg": "RS256",

    "use": "sig",

    "e": "AQAB",

    "n": "6uj6PgDq-bPsdFjiQ6M3yaxMxBUnnYj20xtLciHNafqrygAjnZKjl8LfCO_mtZ7jxfJNCARsz0L3sF9LAtARZqcsUvYLUlNDzflwNTe8woCT7yw0Ml2ZV5BWDbc3izEQnvjlBDGWv9p5jv-D-YNExtIzZKsRKyoy7hSu5FhyxmPfiAXo8b67f0dNy8V8HZfQJ5i9VGyK4Z5xKM-FjHOrC2uIbhzUE6wDe_0M23RTCxj7ZxzXUzZzc-_EBjmZDAI3tI2zBYymO55_gw8zHrNsZ4-32YvNTjBAiTLsjvKlsvNtPTN8q3saoZJWQMSiMi8dRalgA6pUDgcNs5lB9E7tWw"

  }

]


```

### Configure the Worker

1. [Create a new Worker](https://developers.cloudflare.com/workers/get-started/guide/).
2. Copy and paste the example code below into your new Worker, completely replacing any code that already exists.
3. Replace the current zone ID with your zone ID.
4. Replace the current token validation configuration ID with your token validation configuration.
5. Replace the current identity provider’s URL with your identity provider’s key URL.  
Note  
Identity provider URLs can typically be accessed at a known URL specific to your deployment. If you are unsure of the URL, contact your identity provider.
6. If your JWKs URL returns the keys in any JSON object other than `keys`, update the `fetchCredentials()` function to return only the key data.
7. Select **Create** \> **Deploy**.
8. In the Worker settings, go to **Variables** and add an environment variable named `CF_API_TOKEN` with the value of the API token that you have created.
9. In the Worker Triggers, assign a [cron trigger](https://developers.cloudflare.com/workers/configuration/cron-triggers/) to the Worker. Cloudflare recommends a frequent update interval to ensure you always have the latest keys and that an immediate key rotation by your identity provider causes minimal downtime.  
JavaScript example code  
```  
/**  
* Update Token Validation Credentials  
*  
* This example shows how a Cloudflare Workers cron trigger can be used to  
* automatically rotate a JWKs for a Token Configuration.  
*  
* To configure this Worker:  
*  
*   1. Replace `token_config_id` with the ID of the Token Config to update  
*   2. Replace `zone_id` with your Zone ID  
*   3. Replace `url` with a publicly accessible URL with the JWKs you want to use  
*   4. Create a new API Token with "Zone.API Gateway Edit" permissions and add it as a secret with the name `CF_API_TOKEN` (see https://developers.cloudflare.com/workers/configuration/secrets/)  
*  
* This worker also handles GET and POST requests:  
*   - GET will fetch and show the credentials from the provided URL (`GET https://random-worker-name-c134.example.workers.dev/`)  
*   - POST triggers an update and returns the Cloudflare API response of that update (`POST https://random-worker-name-c134.example.workers.dev/`)  
*  
* Use these to test that the Worker is properly configured.  
*  
* After setting up the worker, you can create a cron trigger to run it periodically.  
* For more information on cron triggers, refer to https://developers.cloudflare.com/workers/configuration/cron-triggers/  
*  
* Learn more about Workers at https://developers.cloudflare.com/workers/  
*/  
var zone_id = "760549bc17c54280d6e6ae256c3dd6ae";  
var token_config_id = "91007e72-8f17-46b7-a223-5e57bd333b78";  
var url = "https://cfdata.cloudflareaccess.com/cdn-cgi/access/certs"; // JWKs  
/**  
* fetchCredentials fetches new Token Configuration credentials using the URL defined above.  
* This returns a JSON string with the credentials.  
*  
* Use this function to fetch and parse credentials.  
*  
* @returns {string} credentials  
*/  
async function fetchCredentials() {  
  var requestOptions = {  
    method: "GET",  
    redirect: "follow",  
  };  
  const keys = await fetch(url, requestOptions)  
    .then((e) => e.json())  
    .then((e) => e.keys);  
  return JSON.stringify({ keys: keys });  
}  
/**  
* updateCredentials updates Token Configuration credentials using the Cloudflare API.  
* Credentials are fetched using fetchCredentials, which also does any required processing.  
*  
* @param {string} bearer Cloudflare API Bearer token with "Zone.API Gateway Edit" permissions  
* @returns {string} Cloudflare API response from the update request  
*/  
async function updateCredentials(bearer) {  
  // Cloudflare API endpoint for credentials update  
  const url = `https://api.cloudflare.com/client/v4/zones/${zone_id}/token_validation/config/${token_config_id}/credentials`;  
  const init = {  
    body: await fetchCredentials(),  
    method: "PUT",  
    headers: {  
      Authorization: `Bearer ${bearer}`,  
      "content-type": "application/json;charset=UTF-8",  
    },  
  };  
  const response = await fetch(url, init);  
  return response.text();  
}  
// Export a default object containing event handlers  
export default {  
  /**  
  * fetch handles requests made directly to the Worker.  
  *  
  */  
  async fetch(request, env, ctx) {  
    let responseBody = "";  
    if (request.method === "GET") {  
      responseBody = await fetchCredentials();  
    } else if (request.method === "POST") {  
      responseBody = await updateCredentials(env.CF_API_TOKEN);  
    }  
    return new Response(responseBody, {  
      headers: { "content-type": "application/json;charset=UTF-8" },  
    });  
  },  
  /**  
  * scheduled is the handler for cron triggers.  
  *  
  * For details, refer to https://developers.cloudflare.com/workers/configuration/cron-triggers/  
  *  
  */  
  async scheduled(request, env, ctx) {  
    ctx.waitUntil(updateCredentials(env.CF_API_TOKEN));  
  },  
};  
```

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/jwt-validation/","name":"JSON Web Tokens validation"}},{"@type":"ListItem","position":5,"item":{"@id":"/api-shield/security/jwt-validation/jwt-worker/","name":"Configure the Worker"}}]}
```

---

---
title: Enhance Transform Rules
description: You can forward information from a JSON Web Token (JWT) to the origin in a header by creating Transform Rules using claims that Cloudflare has verified via the JSON Web Token.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/jwt-validation/transform-rules.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Enhance Transform Rules

You can forward information from a [JSON Web Token (JWT)](https://developers.cloudflare.com/api-shield/security/jwt-validation/) to the origin in a header by creating [Transform Rules](https://developers.cloudflare.com/rules/transform/) using claims that Cloudflare has verified via the JSON Web Token.

Claims are available through the `http.request.jwt.claims` firewall fields.

For example, the following expression will extract the user claim from a token processed by the token configuration with `TOKEN_CONFIGURATION_ID`:

```

lookup_json_string(http.request.jwt.claims["<TOKEN_CONFIGURATION_ID>"][0], "claim_name")


```

Refer to [Configure JWT validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/api/) for more information about creating a token configuration.

## Create a Transform Rule

As an example, to send the `x-send-jwt-claim-user` request header to the origin, you must create a Transform Rule:

1. In the Cloudflare dashboard, go to the **Rules overview** page.  
[ Go to **Overview** ](https://dash.cloudflare.com/?to=/:account/:zone/rules/overview)
2. Select **Create rule** \> **Request Header Transform Rules**.
3. Enter a rule name and a filter expression, if applicable.
4. Choose **Set dynamic**.
5. Set the header name to `x-send-jwt-claim-user`.
6. Set the value to:  
```  
lookup_json_string(http.request.jwt.claims["<TOKEN_CONFIGURATION_ID>"][0], "claim_name")  
```  
`<TOKEN_CONFIGURATION_ID>` is your token configuration ID found in JWT validation and `claim_name` is the JWT claim you want to add to the header.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/jwt-validation/","name":"JSON Web Tokens validation"}},{"@type":"ListItem","position":5,"item":{"@id":"/api-shield/security/jwt-validation/transform-rules/","name":"Enhance Transform Rules"}}]}
```

---

---
title: Mutual TLS (mTLS)
description: Mutual TLS (mTLS) authentication is a common security practice that uses client certificates to ensure traffic between client and server is bidirectionally secure and trusted. mTLS also allows requests that do not authenticate via an identity provider — such as Internet-of-things (IoT) devices — to demonstrate they can reach a given resource.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/mtls/index.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Mutual TLS (mTLS)

Note

While API Shield is not required to use mTLS, many teams may use mTLS to protect their APIs.

[Mutual TLS (mTLS)](https://www.cloudflare.com/learning/access-management/what-is-mutual-tls/) authentication is a common security practice that uses client certificates to ensure traffic between client and server is bidirectionally secure and trusted. mTLS also allows requests that do not authenticate via an identity provider — such as Internet-of-things (IoT) devices — to demonstrate they can reach a given resource.

![mTLS sequence diagram](https://developers.cloudflare.com/_astro/api-shield-call-sequence.DjXyNgan_CJbMD.webp) 

Support includes [gRPC ↗](https://grpc.io/docs/what-is-grpc/introduction/)\-based APIs, which use binary formats such as protocol buffers rather than JSON.

## Setup

To set up mTLS for one or more hosts using the dashboard, refer to [Configure mTLS](https://developers.cloudflare.com/api-shield/security/mtls/configure/).

## Availability

All Cloudflare plans can set up mTLS with a Cloudflare-managed certificate authority (CA). Enterprise customers can [upload up to five non-Cloudflare CAs](https://developers.cloudflare.com/ssl/client-certificates/byo-ca/). For higher limits, contact your account team.

## Limitations

When using Yubikeys, the browser may prompt for unlocking the key due to a problem in Yubikey's PKCS#11 library.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/mtls/","name":"Mutual TLS (mTLS)"}}]}
```

---

---
title: Bring your own CA
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/mtls/byo-ca.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Bring your own CA

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/mtls/","name":"Mutual TLS (mTLS)"}},{"@type":"ListItem","position":5,"item":{"@id":"/api-shield/security/mtls/byo-ca/","name":"Bring your own CA"}}]}
```

---

---
title: Configure mTLS
description: When you specify API hosts in mTLS authentication, Cloudflare will block all requests that do not have a client certificate for mTLS authentication.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/mtls/configure.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Configure mTLS

When you specify API hosts in [mTLS authentication](https://developers.cloudflare.com/api-shield/security/mtls/), Cloudflare will block all requests that do not have a [client certificate](https://developers.cloudflare.com/ssl/client-certificates/) for mTLS authentication.

## Prerequisites

Before you can protect your API or web application with mTLS rules, you need to:

* Check that the certificate installed on your origin server matches the hostname of the client certificate, for example `api.example.com`. Origin server wildcard certificates such as `*.example.com` are not supported.
* [Create a client certificate](https://developers.cloudflare.com/ssl/client-certificates/create-a-client-certificate/).
* [Configure your mobile app or IoT device](https://developers.cloudflare.com/ssl/client-certificates/configure-your-mobile-app-or-iot-device/) to use your Cloudflare-issued client certificate.
* [Enable mutual Transport Layer Security (mTLS) for a host](https://developers.cloudflare.com/ssl/client-certificates/enable-mtls/) in your zone.

Note

While API Shield is not required to use mTLS, many teams may use mTLS to protect their APIs.

Warning

By default, API Shield mTLS uses client certificates issued by a Cloudflare-managed CA. If you need to use certificates issued by another CA, you can use the API to [bring your own CA for mTLS](https://developers.cloudflare.com/ssl/client-certificates/byo-ca/).

## Create an mTLS rule via the Cloudflare dashboard

1. In the Cloudflare dashboard, go to **Client Certificates** page.  
[ Go to **Client Certificates** ](https://dash.cloudflare.com/?to=/:account/:zone/ssl-tls/client-certificates)
2. Select **Create a mTLS rule**.
3. In **Custom rules**, several rule parameters have already been filled in. Enter the URI path you want to protect in **Value**.
4. (Optional) Add a `Hostname` field and enter the mTLS-enabled hostnames you wish to protect in **Value**.
5. In **Choose action**, select `Block`.
6. Select **Deploy** to make the rule active.

Once you have deployed your mTLS rule, any requests without a [valid client certificate](https://developers.cloudflare.com/ssl/client-certificates/) will be blocked.

### Expression Builder

To review your mTLS rule in the Expression Builder, select the **wrench icon** associated with your rule.

In the **Expression Preview**, your mTLS rule includes a [compound expression](https://developers.cloudflare.com/ruleset-engine/rules-language/expressions/#compound-expressions) formed from two [simple expressions](https://developers.cloudflare.com/ruleset-engine/rules-language/expressions/#simple-expressions) joined by the `and` operator.

The first expression — `not cf.tls_client_auth.cert_verified` — returns `true` when a request to access your API or web application does not present a valid client certificate.

The second expression uses the `http.request.uri.path` field, combined with the `in` operator, to capture the URI paths your mTLS rule applies to.

Because the [action](https://developers.cloudflare.com/ruleset-engine/rules-language/actions/) for your rule is _Block_, only requests that present a valid client certificate can access the specified hosts.

For enhanced security, Cloudflare recommends that you validate the issuer Subject Key Identifier (SKI) hash alongside the verified certificate field. This ensures that only requests presenting a valid client certificate with a specific issuer are allowed.

You can implement this by using an expression similar to the following:

```

not (cf.tls_client_auth.cert_verified and cf.tls_client_auth.cert_issuer_ski eq "A5AC554235DBA6D963B9CDE0185CFAD6E3F55E9F")


```

To obtain the issuer Subject Key Identifier (SKI) hash of a client certificate stored in the `mtls.crt` file, you can run the following OpenSSL command:

Terminal window

```

openssl x509 -noout -ext authorityKeyIdentifier -in mtls.crt | tail -n1 | tr -d ': '


```

```

A5AC554235DBA6D963B9CDE0185CFAD6E3F55E9F


```

### Check for revoked certificates

To check for [revoked client certificates](https://developers.cloudflare.com/ssl/client-certificates/revoke-client-certificate/), you can either add a new mTLS rule or add a new expression to the [default rule](#expression-builder). To check for revoked certificates, you must use the Expression Builder.

When a request includes a revoked certificate, the `cf.tls_client_auth.cert_revoked` field is set to `true`. If you combined this with the [default mTLS rule](#expression-builder), it would look similar to the following:

```

((not cf.tls_client_auth.cert_verified or cf.tls_client_auth.cert_revoked) and http.request.uri.path in {"/admin"})


```

Warning

This check only applies to client certificates issued by the Cloudflare managed CA. Cloudflare currently does not check certificate revocation lists (CRL) for [CAs that have been uploaded](https://developers.cloudflare.com/ssl/client-certificates/byo-ca/).

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/mtls/","name":"Mutual TLS (mTLS)"}},{"@type":"ListItem","position":5,"item":{"@id":"/api-shield/security/mtls/configure/","name":"Configure mTLS"}}]}
```

---

---
title: Schema validation
description: The API schema defines which API requests are valid based on several request properties like target endpoint, path or query variable format, and HTTP method.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/schema-validation/index.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Schema validation

 Available on all plans 

The API schema defines which API requests are valid based on several request properties like target endpoint, path or query variable format, and HTTP method.

Schema validation allows you to check if incoming traffic complies with a previously supplied API schema. When you provide an API schema or select from a list of learned schema, API Shield creates rules for incoming traffic from the schema definitions. These rules define which traffic is allowed and which traffic gets logged or blocked.

Cloudflare has launched Schema validation 2.0\. For help configuring the previous version of Schema validation for one or more hosts using the dashboard, refer to [Configure Classic Schema validation](https://developers.cloudflare.com/api-shield/reference/classic-schema-validation/). You can make changes to your Classic Schema validation settings but you cannot add any new schemas.

You can migrate to Schema validation 2.0 manually by uploading your schemas to the new system.

---

## Process

Endpoints must be added to [Endpoint Management](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/) for Schema validation to protect them. Uploading a schema via the Cloudflare dashboard will automatically add endpoints, or you can manually add them from [API Discovery](https://developers.cloudflare.com/api-shield/security/api-discovery/).

If you are uploading a schema via the API or Terraform, you must parse the schema and add your endpoints manually.

The API endpoint is the location where API calls or requests are fulfilled. API Shield defines endpoints as a host, method, and path tuple.

Note

To view the contents in your learned schema, refer to [Export a schema](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/schema-learning/#export-a-schema) in Endpoint Management.

---

### Add validation by uploading a schema

* [  New dashboard ](#tab-panel-3164)
* [ Old dashboard ](#tab-panel-3165)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Go to the **Schema validation** tab.
3. Select **Add validation**.
4. Upload a schema file.
5. Select **Add schema and endpoints**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Select **Security** \> **API Shield**.
3. Go to **Schema validation** and select **Add validation**.
4. Select your schema file for upload.
5. Observe the listed endpoints, their host, method, and path. Any new endpoints will automatically be added to Endpoint Management.
6. Choose an action for the non-compliant requests to your endpoints.
7. Select **Add schema and endpoints**.

Note

Changes may take a few minutes to process depending on the number of added endpoints.

### Add validation by applying a learned schema to a single endpoint

* [  New dashboard ](#tab-panel-3166)
* [ Old dashboard ](#tab-panel-3167)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Go to the **Schema validation** tab.
3. Select **Add validation**.
4. Select **Apply learned schema**.
5. Choose an action and select **Apply schema**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Select **Security** \> **API Shield**.
3. Go to **Schema validation** and filter by the learned schema available.
4. Select **Apply learned schema**.
5. Choose an action and select **Apply schema**.

### Add validation by applying a learned schema to an entire hostname

At this time, learned schemas will not overwrite customer-uploaded schemas. If an endpoint is covered by a customer-uploaded schema and also appears in a learned schema, the **Changes** field is set to `Unaffected`.

* [  New dashboard ](#tab-panel-3168)
* [ Old dashboard ](#tab-panel-3169)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Go to the **Schema validation** tab.
3. Select **Add validation**.
4. Select **Apply learned schema**.
5. Choose a hostname and review the endpoints that will be protected by the learned schema.
6. (Optional) Change the action if a request does not match the schema.
7. Select **Apply schema**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Select **Security** \> **API Shield**.
3. Go to **Schema validation** and select **Add validation**.
4. Select **Apply learned schema**.
5. Choose a hostname and review the endpoints that will be protected by the learned schema.
6. (Optional) Change the action if a request does not match the schema.
7. Select **Apply schema**.

Note

If an endpoint is currently protected by a learned schema, the date of the last applied learned schema will be shown in the current schema field.

### Add validation by adding a fallthrough rule

A fallthrough rule acts as a catch-all for requests that do not match endpoints in [Endpoint Management](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/).

By ensuring that all your endpoints in a schema are added to Endpoint Management, the fallthrough action can protect you against legacy or zombie endpoints that your team may be unaware of.

To set up a fallthrough action:

* [  New dashboard ](#tab-panel-3182)
* [ Old dashboard ](#tab-panel-3183)

1. In the Cloudflare dashboard, go to the **Security rules** page.  
[ Go to **Security rules** ](https://dash.cloudflare.com/?to=/:account/:zone/security/security-rules)
2. Select **Templates**.
3. Search for the template named `Mitigate API requests to unidentified endpoints` and select **Preview template**.
4. Give your rule a descriptive name.
5. Choose one or more hostnames from the dropdown menu and select your action.
6. Select **Save as draft** to deploy later, or **Deploy** to deploy now.

Your current fallthrough rules can be viewed in the security rules list.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Go to **Security** \> **API Shield**.
3. Under **Settings**, go to **Fallthrough settings**.
4. Select **Use Template**.
5. Choose one or more hostnames from the drop down menu. The fallthrough rule will act on all traffic that does not match an existing endpoint in Endpoint Management to the selected hostnames.
6. Select **Continue to custom rule**.
7. Name your rule and select your action.
8. Select **Save as draft** to deploy later, or **Deploy** to deploy now.

Your current fallthrough rules can be viewed in the custom rules list.

Note

You can use the `cf.api_gateway.fallthrough_detected` field in your own custom rule for a more customized logic check. This field evaluates as `true` when a request does not match an endpoint in Endpoint Management. Check against your API hostname or root path to ensure that you are not blocking non-API traffic on your zone.

### Change the action of an entire schema

* [  New dashboard ](#tab-panel-3170)
* [ Old dashboard ](#tab-panel-3171)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Go to the **Schema validation** tab.
3. Check the multi-select box to select all endpoints associated with the schema.
4. Select **Change action**.
5. Choose an action from the dropdown menu.
6. Select **Set action**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Select **Security** \> **API Shield**.
3. Go to **Schema validation** and select the schema in the Schema list.
4. Check the multi-select box to select the endpoints shown on the current page.
5. Choose **Select all endpoints**.
6. Select **Change action**.
7. Choose an action from the dropdown menu.
8. Select **Set action**.

### Change the global default action of Schema validation

Schema validation’s default action is visible on the main Schema validation page. This action applies to any endpoint with its action set to `Default`.

* `Log` action: logs events to [Firewall Events](https://developers.cloudflare.com/firewall/).
* `Block` action: blocks requests that fail the schema for an endpoint and logs events to [Firewall Events](https://developers.cloudflare.com/firewall/).
* `None` action: non-compliant requests are neither logged nor blocked.

To change the default action:

* [  New dashboard ](#tab-panel-3172)
* [ Old dashboard ](#tab-panel-3173)

1. In the Cloudflare dashboard, go to the **Security Settings** page.  
[ Go to **Settings** ](https://dash.cloudflare.com/?to=/:account/:zone/security/settings)
2. Filter by **API abuse**.
3. Under **Schema validation** \> **Configurations**, select the edit icon next to **Default action**.
4. Choose a new action from the dropdown menu.
5. Select **Save**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Go to **Security** \> **API Shield**.
3. Select **Schema validation**.
4. Under the default `Log` action, select **Change**.
5. Choose a new action from the dropdown menu.
6. Observe the current action and accept the change by selecting **Change default action** in the popup window.

Alternatively, you can modify the global action via **Security** \> **API Shield** \> **Settings**.

### Change the action of a single endpoint

You can change individual endpoint actions separately from the default action in Schema validation.

This allows you to be stricter on blocking non-compliant requests on certain endpoints when the default action is `Log`. It can also be used to relax constraints on non-compliant requests on certain endpoints when the default action is set to `Block`. You may want to silence known false positives on an endpoint by setting the action to `None`.

To change the action on an individual endpoint:

* [  New dashboard ](#tab-panel-3174)
* [ Old dashboard ](#tab-panel-3175)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Go to the **Schema validation** tab.
3. Search for the endpoint to change.
4. Select the three dots on the endpoint's row > **Change action**.
5. Choose a new action from the dropdown menu and select **Set action**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Go to **Security** \> **API Shield**.
3. Select **Schema validation** and filter the selected endpoint.
4. Select the ellipses on the endpoint's row.
5. Select **Change action**.
6. Choose a new action from the dropdown menu and select **Set action**.

### Disable Schema validation without changing actions

You can disable Schema validation entirely for temporary troubleshooting. You can override all actions at once, preventing Schema validation from taking any action while you complete your troubleshooting.

To disable Schema validation without changing actions:

* [  New dashboard ](#tab-panel-3176)
* [ Old dashboard ](#tab-panel-3177)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Go to the **Schema validation** tab.
3. Select **Schema settings**.
4. Filter by **API abuse**.
5. Turn **Schema validation** off.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Select **Security** \> **API Shield**.
3. Go to the **Schema validation** settings.
4. Select **Disable**.

Your per-endpoint configurations will be saved when modifying the setting, so that you do not lose your configuration. To re-enable your configurations after troubleshooting, navigate back to the settings and select **Enable**.

### View active schemas

* [  New dashboard ](#tab-panel-3178)
* [ Old dashboard ](#tab-panel-3179)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Go to the **Schema validation** tab.
3. Select **Schema settings**.
4. Filter by **API abuse**.
5. View your schemas on **Schema validation** \> **Active schemas**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Select **Security** \> **API Shield**.
3. Go to your **Schema validation** settings.
4. View your schemas under **Uploaded Schemas** and **Learned schemas**.
5. Select **Filter** on the endpoints in either schema.

Note

To export a schema, refer to [Export a schema](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/schema-learning/#export-a-schema).

### Delete active schemas

Deleting the schema will remove validation from the currently associated endpoints, but it will not delete the endpoints from Endpoint Management.

To delete currently uploaded or learned schemas:

* [  New dashboard ](#tab-panel-3180)
* [ Old dashboard ](#tab-panel-3181)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Go to the **Schema validation** tab.
3. Select **Schema settings**.
4. Filter by **API abuse**.
5. View your schemas on **Schema validation** \> **Active schemas**.
6. Select the ellipses to access the menu and download or delete the listed schema.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Select **Security** \> **API Shield**.
3. Go to your **Schema validation** settings.
4. View your schemas under **Uploaded Schemas** and **Learned schemas**.
5. Select the ellipses to access the menu and download or delete the listed schema.

---

## Specifications

Cloudflare currently only accepts [OpenAPI v3 schemas ↗](https://spec.openapis.org/oas/v3.0.3.html). The accepted file formats are YAML (`.yml` or `.yaml` file extension) and JSON (`.json` file extension).

OpenAPI schemas generated by different tooling may not be specific enough to import to Schema validation. We recommend using a third-party tool such as [Swagger Editor ↗](https://swagger.io/tools/swagger-editor/) to ensure that schemas are compliant to the OpenAPI specification.

---

## Limitations

Cloudflare API Shield's Schema validation (importing) and [Schema learning](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/schema-learning/) (exporting) capabilities rely on the [OpenAPI Specification (OAS) v3.0 ↗](https://spec.openapis.org/oas/v3.0.3).

This support includes all patch versions, such as OAS v3.0.x. We do not currently support OAS v3.1 and do not plan to expand support for OpenAPI 2.0.

Note

Cloudflare recommends using a third-party tool like [Swagger Editor ↗](https://editor.swagger.io/) to ensure that all schemas are fully compliant with the OAS v3.0 specification before upload.

Currently, API Shield does not support some features of API schemas, including the following: all responses, external references, non-basic path templating, or unique items.

There is a limit of 10,000 total operations for enabled schemas for Enterprise customers subscribed to [API Shield](https://developers.cloudflare.com/api-shield/). To raise this limit, contact your account team.

### Body size for validation

Schema validation inspects request bodies up to a maximum size that depends on your zone plan. Request bodies that exceed this limit are not validated against your schema, and the configured [Schema validation action](https://developers.cloudflare.com/api-shield/security/schema-validation/#change-the-global-default-action-of-schema-validation) will not apply to those requests.

The default body size limits are:

| Plan       | Default body size limit |
| ---------- | ----------------------- |
| Free       | 1 KB                    |
| Pro        | 8 KB                    |
| Business   | 8 KB                    |
| Enterprise | 128 KB                  |

Note

This limit is separate from the [WAF maximum body inspection size](https://developers.cloudflare.com/waf/managed-rules/#maximum-body-size), which controls how much of the request payload the WAF scans. Increasing one does not affect the other.

#### Identify requests exceeding the body size limit

If Schema validation is blocking or logging requests due to the body size limit, you will see events in **Security** \> **Events** with the Schema validation rule as the source.

For limits on Free, Pro, Business, or Enterprise customers not subscribed to API Shield, refer to [Plans](https://developers.cloudflare.com/api-shield/plans/).

### Required fields

Although not strictly required by the OpenAPI specification, Schema validation strictly requires these fields.

#### `schema`

* [type ↗](https://spec.openapis.org/oas/v3.0.3#schema-object)  
   * All schemas require a type to be set. If the specific type is not supported by Schema validation, it is usually best to simply set the type to `string` instead.

#### `parameter`

* [schema ↗](https://spec.openapis.org/oas/v3.0.3#schema-object)  
   * Schema validation does not support the content field in parameters. For more details, refer to the [notes on validated and supported fields](#notes-on-validated-and-supported-fields) below. Instead, a schema is strictly required on all parameters objects.

### Notes on validated and supported fields

Refer to the information below for more details on Schema validation's current support for various OpenAPI specification (OAS) objects and fields.

#### `servers`

* [url ↗](https://spec.openapis.org/oas/v3.0.3#server-object)  
   * Schema validation does not support relative URLs.
* [variables ↗](https://spec.openapis.org/oas/v3.0.3#server-variable-object)  
   * Server variables are not validated.

#### `parameter`

* [style ↗](https://spec.openapis.org/oas/v3.0.3#parameter-object)  
   * Only the default values are supported: `"simple"` (path or header parameters) and `"form"` (query or cookie parameters).
* [explode ↗](https://spec.openapis.org/oas/v3.0.3#parameter-object)  
   * Only the default values are supported: `true` (for form) and `false` (for simple).
* [content ↗](https://spec.openapis.org/oas/v3.0.3#parameter-object)  
   * The content field is not supported in parameters. Use the schema field instead.
* [type ↗](https://spec.openapis.org/oas/v3.0.3#parameter-object)  
   * Cloudflare currently does not validate object type parameters.

#### `reference`

* [$ref ↗](https://spec.openapis.org/oas/v3.0.3#reference-object)  
   * External or relative references are not supported.

#### `requestBody`

* `content`  
   * [Request Body Object ↗](https://spec.openapis.org/oas/v3.0.3#request-body-object)  
   * [Media Type Object ↗](https://spec.openapis.org/oas/v3.0.3#media-type-object)  
         * Schema validation is able to validate `application/json` documents. If a given schema allows other content types, Schema validation will accept those requests without validation.

#### `parameter/schema`

* `anyOf`  
   * [Parameter Object ↗](https://spec.openapis.org/oas/v3.0.3#parameter-object)  
   * [Schema Object ↗](https://spec.openapis.org/oas/v3.0.3#schema-object)  
         * `anyOf` schemas are currently not supported in parameter schemas.

#### `schema`

* [format ↗](https://spec.openapis.org/oas/v3.0.3#schema-object)  
   * Validated formats:  
         * `date-time`  
         * `time`  
         * `date`  
         * `email`  
         * `hostname`  
         * `ipv4`  
         * `ipv6`  
         * `uri`  
         * `uri-reference`  
         * `iri`  
         * `iri-reference`  
         * `int32`  
         * `int64`  
         * `float`  
         * `double`  
         * `password`  
         * `uuid`  
         * `byte`  
         * `uint64`
* [uniqueItems ↗](https://spec.openapis.org/oas/v3.0.3#schema-object)  
   * This field is currently not validated by Schema validation.

---

## Body inspection

API Shield has the ability to identify body specifications contained in uploaded schemas and validate that the data of incoming API requests adheres to them.

Schema validation currently supports validating requests with content-type `application/json`.

Within the OpenAPI specification, request body schemas are associated to media-ranges (such as `application/*`, `application/xml` or `application/json`).

When Cloudflare validates incoming requests, Cloudflare checks that the request's `content-type` matches the OpenAPI-specified media-range.

For example, when the OpenAPI file specifies `application/*` as part of the request body content map, Cloudflare will accept requests with the content-types `application/xml` and `application/json`. However, only `application/json` bodies will be validated with the supplied schema.

Cloudflare generally recommends keeping the media-ranges as tight as possible. We suggest setting them to an individual media-type. If you need to support multiple content-types on an API endpoint, you can utilize wildcard media-ranges.

Care should also be taken if the origin is configured to perform [MIME sniffing ↗](https://mimesniff.spec.whatwg.org/). For example, when a request carrying a JSON body is deliberately carrying an `application/malicous` content-type and Cloudflare was configured to allow `application/*` media-ranges, the request would be passed along to the origin without validating the JSON body contents. However, an origin that ignores the content-type and either trial deserializes or sniffs the MIME type may deserialize the JSON body with a wrong assumption of having passed schema body validation.

As such, if you need to support `application/json` and `application/xml` on the same endpoint, you can use `application/*`. Cloudflare will validate the provided schema for request bodies where the content-type is set to `application/json`. Requests with content-type `application/xml` (and others matching `application/*`) will be let through. It is still strongly advised to disable content-type sniffing on your origin.

Cloudflare allows specifying the following media-ranges in the OpenAPI request body content map:

* `*/*`
* `application/*`
* `application/json`.

Media-ranges can also be configured to enforce a `charset` parameter. For this, Cloudflare only accepts the `charset` parameter with a static value of `utf-8` as part of the media-range specification and when configured, we will similarly require the request's content-type to carry this charset.

---

## Troubleshooting

This section addresses common issues you may encounter when using schema validation.

### `OneOf` constraint error schema violation in the Security Events

A `OneOf` constraint error means an API request failed schema validation because its body did not match exactly one of the options defined in a [oneOf ↗](https://swagger.io/docs/specification/v3%5F0/data-models/oneof-anyof-allof-not/) list within your uploaded schema.

The request was invalid for one of two reasons:

* **Matches Zero**: The payload did not correctly match any of the available subschemas. This is common when a discriminator field is set, but the payload is missing other required fields for that type.
* **Matches Multiple**: The payload was ambiguous and matched more than one subschema. This happens with generic schemas (for example, if a payload includes both an `email` and a `phone` field, it might match both an `email` and a `phone` schema definition, violating the "exactly one" rule).

To fix this, check the failing request body against the API schema definition. It will either be missing required fields for the intended type or include properties from multiple different, conflicting types that make it ambiguous.

---

## Availability

Schema validation is available for all customers. Refer to [Plans](https://developers.cloudflare.com/api-shield/plans/) for more information based on your plan type.

[Schema learning](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/schema-learning/) is only available for customers subscribed to API Shield.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/schema-validation/","name":"Schema validation"}}]}
```

---

---
title: Configure Schema validation via the API
description: Schema validation 2.0 allows all corresponding configuration calls to be made via API. This validation centers more around individual endpoints and lets you set mitigation actions for each endpoint individually. Additionally, you can use Cloudflare-provided learned schemas that we learn automatically from your traffic for individual endpoints.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/schema-validation/api.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Configure Schema validation via the API

Schema validation 2.0 allows all corresponding configuration calls to be made via API. This validation centers more around individual endpoints and lets you set mitigation actions for each endpoint individually. Additionally, you can use Cloudflare-provided learned schemas that we [learn automatically](https://developers.cloudflare.com/api-shield/management-and-monitoring/#endpoint-schema-learning) from your traffic for individual endpoints.

Note

[Classic Schema validation documentation](https://developers.cloudflare.com/api-shield/reference/classic-schema-validation/) is available for reference only.

## Upload schemas via the API to Schema validation

1. Upload a schema.
2. Ensure that your endpoints are added in Endpoint Management.
3. Set the schema to `active` if it is not already done.
4. Set the Schema validation zone-wide action from `none` to `log`.
5. Send test traffic that violates the schema.
6. View test traffic in Security Events by filtering for **Service** \> **API Shield - Schema validation**.
7. Optional:  
   * Set a single endpoint to `block`.  
   * Set the Schema validation zone-wide to `block`.  
   * Temporarily override all schemas zone-wide to `none`.  
   * Remove the temporary override.

Cloudflare recommends you to rerun test traffic and monitor the HTTP response codes after changing any settings to ensure Schema validation is operating as expected.

Settings changes may take a few minutes to implement.

Note

Endpoints must be listed in Endpoint Management for Schema validation to match requests.

## Configuration

### Upload and activate a schema

Upload a schema via the v4 API using `POST`. This example requires a `example_schema.yaml` schema file in the current folder.

Required API token permissions

At least one of the following [token permissions](https://developers.cloudflare.com/fundamentals/api/reference/permissions/)is required:
* `Account API Gateway`
* `Domain API Gateway`

Upload a schema

```

curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/schema_validation/schemas" \

  --request POST \

  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \

  --json '{

    "kind": "openapi_v3",

    "name": "example_schema",

    "source": "<SOURCE>",

    "validation_enabled": true

  }'


```

```

{

    "result":

    {

        "schema":

        {

            "schema_id": "af632e95-c986-4738-a67d-2ac09995017a",

            "name": "example_schema",

            "kind": "openapi_v3",

            "source": "<SOURCE>",

            "created_at": "2023-04-03T15:10:08.902309Z"

        }

    },

    "success": true,

    "errors":

    [],

    "messages":

    []

}


```

By default, Schema validation is disabled for an uploaded schema so that you can inspect it first. You can upload a schema and enable it immediately by setting the form parameter `validation_enabled=true`.

Use a `PATCH` request to activate a schema after inspection.

Required API token permissions

At least one of the following [token permissions](https://developers.cloudflare.com/fundamentals/api/reference/permissions/)is required:
* `Account API Gateway`
* `Domain API Gateway`

Enable validation for a schema

```

curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/api_gateway/user_schemas/$SCHEMA_ID" \

  --request PATCH \

  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \

  --json '{

    "validation_enabled": true

  }'


```

```

{

    "result":

    {

        "schema_id": "0bf58160-5da3-48ac-80a9-069f9642c1a0",

        "name": "api_schema.json",

        "kind": "openapi_v3",

        "validation_enabled": true,

        "created_at": "0001-01-01T00:00:00Z"

    },

    "success": true,

    "errors":

    [],

    "messages":

    []

}


```

When a schema is active, it executes the mitigation action specified for each operation. Refer to [change the default and operation-specific mitigation action](#change-the-default-and-operation-specific-mitigation-action).

### Add new operations to Endpoint Management

Schemas contain a set of servers, paths, and methods, which together define an operation. Schema validation only acts on the requests to operations which have been added to the API Shield Endpoint Management. If a schema contains operations which have not been added to Endpoint Management, they can be retrieved together with the configuration information about added operations.

cURL command

```

curl --request GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/user_schemas/{schema_id}/operations?feature=schema_info&operation_status=new&page=1&per_page=5000" \

--header "Authorization: Bearer <API_TOKEN>" \

--header 'Content-Type: application/json'


```

```

{

    "result":

        [

          {

              "method": "GET",

              "host": "example.com",

              "endpoint": "/pets"

          }

     ],

    "success": true,

    "errors": [],

    "messages": [],

    "result_info": {

        "page": 1,

        "per_page": 30,

        "count": 1,

        "total_count": 1

    }

}


```

To receive information about the configuration of existing operations, Cloudflare recommends passing the `?feature=schema_info` parameter.

You can add new operations in a schema to Endpoint Management using `POST`.

cURL command

```

curl "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/operations" \

--header "Authorization: Bearer <API_TOKEN>" \

--header 'Content-Type: application/json' \

--data '[

  {

   "method": "GET",

   "host": "example.com",

   "endpoint": "/pets",

  }

]'


```

```

{

    "result":  [

            {

                "operation_id": "6c734fcd-455d-4040-9eaa-dbb3830526ae",

                "method": "GET",

                "host": "example.com",

                "endpoint": "/pets",

                "last_updated": "2023-04-04T16:07:37.575971Z"

         }

     ],

    "success": true,

    "errors":

    [],

    "messages":

    []

}


```

You can add all operations in a schema that do not already exist in Endpoint Management by combining two commands as one. There is a maximum of 20 operations for this API call. The example requires the `jq` tool.

cURL command

```

curl --silent "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/operations" \

--header "Authorization: Bearer <API_TOKEN>" \

--header "Content-Type: application/json" \

--data "$(curl --silent "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/user_schemas/{schema_id}/operations?feature=schema_info&page=1&per_page=5000" --header "Authorization: Bearer <API_TOKEN>" | jq ".result")"


```

Note

If you run this command again immediately, it will result in an error as all `new_operations` are now `existing_operations`.

### Change the default and operation-specific mitigation action

If a schema is uploaded and active for a set of operations, it validates incoming requests to each operation and decides whether a mitigation action should be taken. This mitigation action is defined per operation and can take the values **none**, **log**, and **block**, which correspond to no action, logging the requests, or blocking them before they reach the origin.

New operations will not have a mitigation action set and will use the zone-wide default mitigation action. The current default mitigation action can be retrieved using `GET`.

cURL command

```

curl "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/settings/schema_validation" \

--header "Authorization: Bearer <API_TOKEN>"


```

```

{

    "result":  {

        "validation_default_mitigation_action": "none",

        "validation_override_mitigation_action": null

    }

    "success": true,

    "errors":

    [],

    "messages":

    []

}


```

A new value out of `none`, `log`, and `block` can be set using `PUT`.

cURL command

```

curl --request PUT "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/settings/schema_validation" \

--header "Authorization: Bearer <API_TOKEN>" \

--header "Content-Type: application/json" \

--data '{

  "validation_default_mitigation_action": "block"

}'


```

```

{

    "result":  {

        "validation_default_mitigation_action": "block",

        "validation_override_mitigation_action": null

    }

    "success": true,

    "errors":

    [],

    "messages":

    []

}


```

If the mitigation action for an individual operation is of interest, the current value can be retrieved with `GET` using the operation ID.

cURL command

```

curl "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/operations/{operation_id}/schema_validation" \

--header "Authorization: Bearer <API_TOKEN>"


```

```

{

    "result":  {

        "mitigation_action": "null"

    }

    "success": true,

    "errors":

    [],

    "messages":

    []

}


```

If the value is `null`, it means that no mitigation action has been specified for this operation and the default mitigation action is being used.

You can set the mitigation action to a value out of `none`, `block`, `log`, and `null` by using `PUT`.

cURL command

```

curl --request PUT "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/operations/{operation_id}/schema_validation" \

--header "Authorization: Bearer <API_TOKEN>" \

--header "Content-Type: application/json" \

--data '{

    "mitigation_action": "block"

}'


```

```

{

    "result":  {

        "mitigation_action": "block"

    }

    "success": true,

    "errors":

    [],

    "messages":

    []

}


```

### List all schemas

You can get an overview of the schemas currently active on a zone using `GET`.

`validation_enabled=true` is an optional parameter.

Required API token permissions

At least one of the following [token permissions](https://developers.cloudflare.com/fundamentals/api/reference/permissions/)is required:
* `Account API Gateway`
* `Account API Gateway Read`
* `Domain API Gateway`
* `Domain API Gateway Read`

List all uploaded schemas

```

curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/schema_validation/schemas" \

  --request GET \

  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"


```

```

{

    "result":  [

        {

          "schema_id": "af632e95-c986-4738-a67d-2ac09995017a",

          "name": "example_schema",

          "kind": "openapi_v3",

          "source": "<SOURCE>",

          "created_at": "2023-04-03T15:10:08.902309Z"

      }

    ]

    "success": true,

    "errors":

    [],

    "messages":

    []

}


```

Note

We recommend using the query parameter `omit_source=true` to only display active schemas and not retrieve the source for every schema to get less output.

### Delete a schema

You can delete a schema using `DELETE`.

Required API token permissions

At least one of the following [token permissions](https://developers.cloudflare.com/fundamentals/api/reference/permissions/)is required:
* `Account API Gateway`
* `Domain API Gateway`

Delete a schema

```

curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/schema_validation/schemas/$SCHEMA_ID" \

  --request DELETE \

  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"


```

```

{

    "result":  null,

    "success": true,

    "errors":

    [],

    "messages":

    []

}


```

### Activate a learned schema for an operation

Cloudflare provides automatically learned parameter schemas for all operations in Endpoint Management with a sufficient amount of requests. A learned schema can be inspected using `GET`.

cURL command

```

curl "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/operations/{operation_id}?feature=parameter_schemas" \

--header "Authorization: Bearer <API_TOKEN>"


```

```

{

    "result":

    {

        "operation_id": "5c734fcd-455d-4040-9eaa-dbb3830526ae",

        "method": "PATCH",

        "host": "example.com",

        "endpoint": "/pets",

        "last_updated": "2023-04-04T16:07:37.575971Z",

        "features":

        {

            "parameter_schemas":

            {

                "last_updated": "2023-04-03T20:11:55.879006Z",

                "parameter_schemas":

                {

                    "responses": null,

                    "parameters":

                    [

                        {

                            "in": "query",

                            "name": "var1",

                            "schema":

                            {

                                "type": "string"

                            },

                            "required": true,

                            "description": "Sufficient requests have been observed for this parameter to provide high confidence in this parameter schema."

                        }

                    ],

                    "x-cf-parameter-schemas": "operation schema with automatically learned path and query parameters"

                }

            }

        }

    },

    "success": true,

    "errors":

    [],

    "messages":

    []

}


```

If you are satisfied with the inspected parameter schema, you can add and activate it using `PUT`.

cURL command

```

curl --request PUT "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/operations/{operation_id}/cloudflare_learned_schema?timestamp=2023-04-03T20:11:55.879006Z" \

--header "Authorization: Bearer <API_TOKEN>"


```

```

{

    "result": null,

    "success": true,

    "errors":

    [],

    "messages":

    []

}


```

Note

Parameter schemas are updated between every 24 hours up to one week. To ensure that a parameter schema has not been updated during the inspection, Cloudflare recommends that you pass the `last_updated` timestamp of the parameter-schema feature (not the `last_updated` of the whole operation) as an identifier in the timestamp query parameter.

### Disable Schema validation

To quickly disable Schema validation for a whole zone, use `PATCH`. This operation will override all operation-mitigation actions.

cURL command

```

curl --request PATCH "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/settings/schema_validation" \

--header "Authorization: Bearer <API_TOKEN>" \

--header 'Content-Type: application/json' \

--data '{

  "validation_override_mitigation_action": "none"

}'


```

```

{

    "result":  {

        "validation_default_mitigation_action": "block",

        "validation_override_mitigation_action": "none"

    }

    "success": true,

    "errors":

    [],

    "messages":

    []

}


```

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/schema-validation/","name":"Schema validation"}},{"@type":"ListItem","position":5,"item":{"@id":"/api-shield/security/schema-validation/api/","name":"Configure Schema validation via the API"}}]}
```

---

---
title: Sequence Analytics
description: Sequence Analytics tracks the order of API endpoint requests over time, allowing you to discover how users interact with your API. Sequence Analytics groups and highlights important user journeys (sequences) across your API. You can enforce preferred sequences using Sequence mitigation.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/sequence-analytics.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Sequence Analytics

Sequence Analytics tracks the order of API endpoint requests over time, allowing you to discover how users interact with your API. Sequence Analytics groups and highlights important user journeys (sequences) across your API. You can enforce preferred sequences using [Sequence mitigation](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/).

## Process

### Sequence building

A sequence is a time-ordered list of HTTP API requests made by a specific visitor as they browse a website, use a mobile app, or interact with a B2B partner via API.

For example, a portion of a sequence made during a bank funds transfer could look like:

| Order | Method | Path                                   | Description                                                                                                                                    |
| ----- | ------ | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| 1     | GET    | /api/v1/users/{user\_id}/accounts      | user\_id is the active user.                                                                                                                   |
| 2     | GET    | /api/v1/accounts/{account\_id}/balance | account\_id is one of the user’s accounts.                                                                                                     |
| 3     | GET    | /api/v1/accounts/{account\_id}/balance | account\_id is a different account belonging to the user.                                                                                      |
| 4     | POST   | /api/v1/transferFunds                  | This contains a request body detailing an account to transfer funds from, an account to transfer funds to, and an amount of money to transfer. |

API Shield uses your configured session identifier and your saved endpoints to build a set of ordered API operations (HTTP host, method, and path) requested per session. We may surface sequences in various lengths depending how API Shield scores the sequences.

### Sequence scoring

API Shield scores sequences by a metric called precedence score. Sequence Analytics displays sequences by the highest precedence score. High-scoring sequences contain API requests which are likely to occur together in order.

Using the example above, a high score means that the last operation in the sequence `POST /api/v1/transferFunds` is highly likely to be preceded by the other operations in sequence `GET /api/v1/users/{user_id}/accounts` followed by `GET /api/v1/accounts/{account_id}/balance`. The scores are probabilities, which API Shield estimates using data from the last 24 hours.

### Secure your API

To proactively secure your API, you should inspect your highest-scoring sequences. For each high-scoring sequence, you should confirm with your development team if the final operation in the sequence must legitimately always be preceded by the other operations in the sequence.

Using the above example, if `POST /api/v1/transferFunds` must legitimately always be preceded by `GET /api/v1/users/{user_id}/accounts` and `GET /api/v1/accounts/{account_id}/balance?`, you should create an **Allow** rule in sequence mitigation on the final operation of the sequence.

You should also consider applying other API Shield protections to these endpoints ([rate limiting suggestions](https://developers.cloudflare.com/api-shield/security/volumetric-abuse-detection/), [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/), [JWT validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/), and [mTLS](https://developers.cloudflare.com/api-shield/security/mtls/)).

For more information, refer to our [blog post ↗](https://blog.cloudflare.com/api-sequence-analytics).

### Repeated sequences

True API usage shows many successively repeated operations. To facilitate exploration, Sequence Analytics collapses successively repeated operations into one.

## Availability

Sequence Analytics is available for all API Shield customers. Pro, Business, and Enterprise customers who have not purchased API Shield can get started by [enabling the API Shield trial ↗](https://dash.cloudflare.com/?to=/:account/:zone/security/api-shield) in the Cloudflare dashboard or contacting your account manager.

## Limitations

Sequence Analytics currently requires a session identifier and saved endpoints in order to build and track sequences made by an API consumer. Ensure that you have [set up your session identifier(s)](https://developers.cloudflare.com/api-shield/get-started/#session-identifiers) and [saved your endpoints](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/).

Sequences are currently limited to nine operations in length.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/sequence-analytics/","name":"Sequence Analytics"}}]}
```

---

---
title: Sequence mitigation
description: Sequence mitigation allows you to enforce request patterns for authenticated clients communicating with your API.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/sequence-mitigation/index.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Sequence mitigation

Sequence mitigation allows you to enforce request patterns for authenticated clients communicating with your API.

You can use sequence rules to establish a set of known behavior for API clients or detect and mitigate malicious behavior.

For example, you may expect that API requests made during a bank funds transfer could conform to the following order in time:

| Order | Method | Path                                   | Description                                                                                                                                    |
| ----- | ------ | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| 1     | GET    | /api/v1/users/{user\_id}/accounts      | user\_id is the active user.                                                                                                                   |
| 2     | GET    | /api/v1/accounts/{account\_id}/balance | account\_id is one of the user’s accounts.                                                                                                     |
| 3     | GET    | /api/v1/accounts/{account\_id}/balance | account\_id is a different account belonging to the user.                                                                                      |
| 4     | POST   | /api/v1/transferFunds                  | This contains a request body detailing an account to transfer funds from, an account to transfer funds to, and an amount of money to transfer. |

You may want to enforce that an API user requests `GET /api/v1/users/{user_id}/accounts` before `GET /api/v1/accounts/{account_id}/balance` and that you request `GET /api/v1/accounts/{account_id}/balance` before `POST /api/v1/transferFunds`.

Using sequence mitigation, you can enforce that request pattern with two new sequence mitigation rules.

Note

You can create sequence mitigation rules for a sequence even if the sequence is not listed in [Sequence Analytics](https://developers.cloudflare.com/api-shield/security/sequence-analytics/).

## Process

You can [create a sequence rule](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/manage-sequence-rules/) to enforce behavior on your API over time in two different ways. Sequence rules can either protect an endpoint from users performing a known specific sequence of API calls (otherwise known as a negative security model) or from users making API requests outside of your expectations (otherwise known as a positive security model).

Sequence rules built via the Cloudflare dashboard using API Shield rules utilize a lookback window to match endpoints in the sequence. The rule will match as long as both endpoints are found within [10 requests](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/#request-limitations) (to endpoints within Endpoint Management) of each other and made within [10 minutes](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/#time-limitations) of each other.

Note

Contact your account team if the default lookback window is not sufficient for you.

If you want to add multiple endpoints, ignore the lookback window, and configure time-based constraints, refer to [Sequence mitigation custom rules](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/custom-rules/).

In the bank funds transfer example, enforcing that a user requests `GET /api/v1/accounts/{account_id}/balance` before `POST /api/v1/transferFunds` is considered a positive security model, since a user may only perform a funds transfer after listing an account balance.

A negative security model may be useful if you see abusive behavior that is outside the norm of your application and you need to stop the requests while researching the correct positive security model to implement.

For example, if there was an authorization bug that allowed users to iterate through other users' profiles that contain account numbers via `GET /api/v1/users/{var1}/profile` and then a user tries to make fradulent funds transfers, you could create up a rule to block or log the sequence `GET /api/v1/users/{var1}/profile` to `POST /api/v1/transferFunds`.

## Limitations

### Endpoint Management

To track requests to API endpoints, they must be added to [Endpoint Management](https://developers.cloudflare.com/api-shield/management-and-monitoring/). Add your endpoints to endpoint management via [API Discovery](https://developers.cloudflare.com/api-shield/security/api-discovery/), [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/), or [manually](https://developers.cloudflare.com/api-shield/management-and-monitoring/#add-endpoints-manually) through the Cloudflare dashboard.

### Session Identifiers

API Shield uses your configured session identifier to track sessions. You must configure a session identifier that is unique per end user of your API in order for sequence mitigation to function as expected.

### Request limitations

By default, API Shield stores the current and previous nine requested endpoints by each individual API user identified through the session identifier. Contact your account team if the default lookback window is not sufficient for you.

Sequence mitigation further de-duplicates requests to the same endpoint while building the sequence.

To illustrate, in the original [sequence example](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/) listed above, sequence mitigation would store the following sequence:

1. `GET /api/v1/users/{user_id}/accounts`
2. `GET /api/v1/accounts/{account_id}/balance`
3. `POST /api/v1/transferFunds`

Sequence mitigation de-duplicated the two requests to `GET /api/v1/accounts/{account_id}/balance` and stored them as a single request.

### Time limitations

Sequence mitigation rules have a lookback period of 10 minutes, which means that any two requests using the same session identifier will extend the sequence if they happen no further than 10 minutes apart. A request for a session identifier that happens 10 minutes after the last one will start recording a new sequence. For example, if you create a rule that one endpoint must be requested before another endpoint, and more than 10 minutes elapses between a user requesting each endpoint, the rule will not match.

## Availability

Sequence mitigation is currently in a closed beta and is only available for Enterprise customers. If you would like to be included in the beta, contact your account team.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/sequence-mitigation/","name":"Sequence mitigation"}}]}
```

---

---
title: Configure sequence mitigation via the API
description: Configuring sequence mitigation via the API consists of building a rule object by choosing the sequence and setting the type of rule and its action.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/sequence-mitigation/api.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Configure sequence mitigation via the API

Configuring sequence mitigation via the API consists of building a rule object by choosing the sequence and setting the type of rule and its action.

Example of a rule object

```

{

    "id": "d4909253-390f-4956-89fd-92a5b0cd86d8",

    "title": "<RULE_TITLE>",

    "kind": "allow",

    "action": "block",

    "sequence": [

     "0d9bf70c-92e1-4bb3-9411-34a3bcc59003",

     "b704ab4d-5be0-46e0-9875-b2b3d1ab42f9"

    ],

    "priority": 0,

    "last_updated": "2023-07-24T12:06:51.796286Z",

    "created_at": "2023-07-24T12:06:51.796286Z"

}


```

This rule enforces that a request to endpoint `0d9bf70c-92e1-4bb3-9411-34a3bcc59003` must come before a request to endpoint `b704ab4d-5be0-46e0-9875-b2b3d1ab42f9`.

Otherwise, the request to endpoint `b704ab4d-5be0-46e0-9875-b2b3d1ab42f9` is blocked.

### Fields

| Field name    | Description                                                                                                                                                                                                                                           | Possible Values                                                | Example                                                                            |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| id            | An opaque identifier that identifies a rule.                                                                                                                                                                                                          | A UUID                                                         | "d4909253-390f-4956-89fd-92a5b0cd86d8"                                             |
| title         | A string that helps to identify the rule.                                                                                                                                                                                                             | A value between 1 and 50 characters                            | "Allow checkout sequence"                                                          |
| kind          | Defines the semantics of this rule. Block rules have a negative security model and allow to explicitly deny a sequence. Allow rules have a positive security model and deny everything but the configured sequence.                                   | block, allow                                                   | "block"                                                                            |
| action        | What firewall action should we do when the rule matches.                                                                                                                                                                                              | block,log                                                      | "log"                                                                              |
| sequence      | Denotes the operations (from Endpoint Management) that make up the sequence for this rule. We currently only support sequences of length two. The first operation will be the starting endpoint and the second operation will be the ending endpoint. | An array with two valid operation IDs from Endpoint Management | \["0d9bf70c-92e1-4bb3-9411-34a3bcc59003", "b704ab4d-5be0-46e0-9875-b2b3d1ab42f9"\] |
| priority      | Denotes the precedence of this rule in relation to all other rules. Rules with a higher priority value are evaluated before those with a lower value. If two rules have the same priority, they are evaluated in the order in which they were added.  | A valid integer                                                | 10                                                                                 |
| last\_updated | When this rule was last changed.                                                                                                                                                                                                                      | A date string                                                  | 2023-05-02T12:06:51.796286Z                                                        |
| created\_at   | When this rule was created.                                                                                                                                                                                                                           | A date string                                                  | 2023-05-02T12:06:51.796286Z                                                        |

You can find an endpoint's operation ID by exporting the schema in [Endpoint Management](https://developers.cloudflare.com/api-shield/management-and-monitoring/#export-a-schema) or via the [API](https://developers.cloudflare.com/api/resources/api%5Fgateway/subresources/operations/methods/list/).

### List sequence rules

Use the `GET` command to list rules.

cURL command

```

curl "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/seqrules"


```

### Add a single sequence rule

Use the `POST` command to create a single rule.

This adds a single rule to all existing rules. Priority can be used to place the rule between, before, or after another rule.

The response will reflect the rule that has been written with its ID. In case something is not right with the rule, an appropriate error message with a `json` path pointing towards the issue will be provided.

Example using cURL

```

curl "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/seqrules/rules" \

--header "Content-Type: application/json" \

--data '{

  "title": "string",

  "kind": "block",

  "action": "block",

  "sequence": [

    "0d9bf70c-92e1-4bb3-9411-34a3bcc59003",

    "b704ab4d-5be0-46e0-9875-b2b3d1ab42f9"

  ],

  "priority": 0

}'


```

### Add multiple sequence rules

Use the `PUT` command to set up new rules in bulk.

This will overwrite any existing rules and replace them with the rules specified in the body. Setting an empty array for the rules removes all rules.

The response will reflect the rules that have been written with their IDs in case something is not right with the rules, an appropriate error message with a `json` path pointing towards the issue will be provided.

Example using cURL

```

curl --request PUT "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/seqrules" \

--header "Content-Type: application/json" \

--data '{

  "rules": [

    {

      "title": "<RULE_TITLE>",

      "kind": "block",

      "action": "block",

      "sequence": [

        "0d9bf70c-92e1-4bb3-9411-34a3bcc59003",

        "b704ab4d-5be0-46e0-9875-b2b3d1ab42f9"

      ],

      "priority": 0

    }

  ]

}'


```

### Delete a rule

Use the `DELETE` command with its rule ID to delete a rule.

cURL command

```

curl --request DELETE "https://api.cloudflare.com/client/v4/zones/{zone_id}/api_gateway/seqrules/rules/d4909253-390f-4956-89fd-92a5b0cd86d8"


```

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/sequence-mitigation/","name":"Sequence mitigation"}},{"@type":"ListItem","position":5,"item":{"@id":"/api-shield/security/sequence-mitigation/api/","name":"Configure sequence mitigation via the API"}}]}
```

---

---
title: Sequence mitigation custom rules
description: API Shield sequence custom rules use the configured API Shield session identifier to track the order of requests a user has made and the time between requests, and makes them available via Cloudflare Rules. This allows you to write rules that match valid or invalid sequences.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/sequence-mitigation/custom-rules.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Sequence mitigation custom rules

API Shield sequence custom rules use the configured API Shield session identifier to track the order of requests a user has made and the time between requests, and makes them available via [Cloudflare Rules](https://developers.cloudflare.com/rules). This allows you to write rules that match valid or invalid sequences.

These rules are similar to [cookie sequence rules](https://developers.cloudflare.com/bots/additional-configurations/sequence-rules/) but have a different set of prerequisties:

* They also need the `fraud_acct_ent` entitlement on a Cloudflare account.
* They require [session identifiers](https://developers.cloudflare.com/api-shield/get-started/#session-identifiers) to be set in API Shield.
* Because they require session identifiers, they can only be used on traffic that can be clearly attributed to individual users through session identifiers (authenticated traffic).
* Because Cloudflare stores the user state in memory and not in a cookie, a session's sequence lifetime is limited to 10 minutes.
* You must set up at least one [API sequence rule](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/manage-sequence-rules/) to activate the sequence system.

Rules built using these custom rules are similar to the sequence rules that can be configured [via the API or the Cloudflare dashboard](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/) as they make use of the same underlying technology. However, these custom rules allow for greater flexibility by using free-form logic on top of the recorded sequence and providing access to the full response options that rulesets offers.

## Availability

Note

Sequence mitigation is currently in a closed beta and is only available for Enterprise customers. If you would like to be included in the beta, contact your account team.

These sequence fields are available in:

* [Custom rules](https://developers.cloudflare.com/waf/custom-rules/) (`http_request_firewall_custom` phase)
* [Rate limiting rules](https://developers.cloudflare.com/waf/rate-limiting-rules/) (`http_request_ratelimit`)
* [Bulk Redirects](https://developers.cloudflare.com/workers/examples/bulk-redirects/) (`http_request_redirect`)
* [Request Header Transform Rules](https://developers.cloudflare.com/rules/transform/response-header-modification/) (`http_request_late_transform`)

| Field name                             | Description                                                                                                                                                                                                                                                                  | Example value                          |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
| cf.sequence.current\_opString          | This field contains the ID of the operation that matches the current request. If the current request does not match any operations defined in Endpoint Management, it will be an empty string.                                                                               | c821cc00                               |
| cf.sequence.previous\_opsArray<String> | This field contains an array of the prior operation IDs in the sequence, ordered from most to least recent. It does not include the current request.  If an operation is repeated, it will appear multiple times in the sequence.                                            | \["f54dac32", "c821cc00", "a37dc89b"\] |
| cf.sequence.msec\_since\_opMap<Number> | This field contains a map where the keys are operation IDs and the values are the number of milliseconds since that operation has most recently occurred.  This does not include the current request or operation as it only factors in previous operations in the sequence. | {"f54dac32": 1000, "c821cc00": 2000}   |

## Build a sequence custom rule

* [  New dashboard ](#tab-panel-3184)
* [ Old dashboard ](#tab-panel-3185)

1. In the Cloudflare dashboard, go to the **Security rules** page.  
[ Go to **Security rules** ](https://dash.cloudflare.com/?to=/:account/:zone/security/security-rules)
2. To create a new empty rule, select **Create rule** \> **Custom rules**.
3. Enter a descriptive name for the rule in **Rule name**.
4. Under **When incoming requests match**, use the **Field** drop-down list to filter by **Sequences** and select from:  
   * Current Operation  
   * Previous Operations  
   * Elapsed time
5. Under **Value**, select the edit icon to use Builder and build a sequence on the side panel.
6. Under **Select a hostname for this sequence**, choose all or a specific hostname from the dropdown list. Optionally, you can use the search bar to search for a specific hostname.
7. From the **Methods** dropdown list, choose all methods or a specific request method.
8. Select the checkbox for each endpoint in the order that you want them to appear in the sequence.
9. Set the time to complete.
10. Select **Save**.
11. Under **Then take action**, select the rule action in the **Choose action** dropdown. For example, selecting _Block_ tells Cloudflare to refuse requests that match the conditions you specified.
12. (Optional) If you selected the _Block_ action, you can configure a custom response.
13. Under **Place at**, select the order of when the rule will fire.
14. To save and deploy your rule, select **Deploy**. If you are not ready to deploy your rule, select **Save as Draft**.

Note

The fields in the custom rule are populated as a grouped sequence based on the values that you entered on Builder.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Go to **Security** \> **WAF** \> **Custom rules**.
3. To create a new empty rule, select **Create rule**.
4. Enter a descriptive name for the rule in **Rule name**.
5. Under **When incoming requests match**, use the **Field** drop-down list and select:  
   * Current Operation  
   * Previous Operations  
   * Elapsed time
6. Under **Value**, build a sequence by selecting a hostname for the sequence.
7. Select the checkbox for each endpoint in the order that you want them to appear in the sequence.
8. Set the time to complete.
9. Select **Save**.
10. Under **Then take action**, select the rule action in the **Choose action** dropdown. For example, selecting _Block_ tells Cloudflare to refuse requests that match the conditions you specified.
11. (Optional) If you selected the _Block_ action, you can configure a custom response.
12. Under **Place at**, select the order of when the rule will fire.
13. To save and deploy your rule, select **Deploy**. If you are not ready to deploy your rule, select **Save as Draft**.

### Example rules

Each saved endpoint will have an endpoint ID visible in its details page in Endpoint Management in the form of a UUID. The references below (`aaaaaaaa`, `bbbbbbbb`, and `cccccccc`) are the first eight characters of the endpoint ID.

The visitor must wait more than 2 seconds after requesting endpoint `aaaaaaaa` before requesting endpoint `bbbbbbbb`:

```

cf.sequence.current_op eq "bbbbbbbb" and

cf.sequence.msec_since_op["aaaaaaaa"] ge 2000


```

The visitor must request endpoints `aaaaaaaa`, then `bbbbbbbb`, then `cccccccc` in that exact order:

```

cf.sequence.current_op eq "cccccccc" and

cf.sequence.previous_ops[0] == "bbbbbbbb" and

cf.sequence.previous_ops[1] == "aaaaaaaa"


```

The visitor must request endpoint `aaaaaaaa` before endpoint `bbbbbbbb`, but endpoint `aaaaaaaa` can be anywhere in the previous 10 requests:

```

cf.sequence.current_op eq "bbbbbbbb" and

any(cf.sequence.previous_ops[*] == "aaaaaaaa")


```

The visitor must request either endpoint `aaaaaaaa` before endpoint `bbbbbbbb`, or endpoint `cccccccc` before endpoint `bbbbbbbb`:

```

(cf.sequence.current_op eq "bbbbbbbb" and

any(cf.sequence.previous_ops[*] == "aaaaaaaa")) or

(cf.sequence.current_op eq "bbbbbbbb" and

any(cf.sequence.previous_ops[*] == "cccccccc"))


```

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/sequence-mitigation/","name":"Sequence mitigation"}},{"@type":"ListItem","position":5,"item":{"@id":"/api-shield/security/sequence-mitigation/custom-rules/","name":"Sequence mitigation custom rules"}}]}
```

---

---
title: Manage sequence rules
description: Cloudflare recommends creating sequence rules using WAF custom rules. Refer to the sequence custom rules documentation for more information.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/sequence-mitigation/manage-sequence-rules.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Manage sequence rules

Cloudflare recommends creating sequence rules using WAF custom rules. Refer to the [sequence custom rules documentation](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/custom-rules/) for more information.

Note

Sequence mitigation is currently in a closed beta and is only available for Enterprise customers. If you would like to be included in the beta, contact your account team.

## Create a sequence rule

* [  New dashboard ](#tab-panel-3186)
* [ Old dashboard ](#tab-panel-3187)

1. In the Cloudflare dashboard, go to the **Security rules** page.  
[ Go to **Security rules** ](https://dash.cloudflare.com/?to=/:account/:zone/security/security-rules)
2. Select **Create rule** and choose **API sequence rules**.
3. Name your rule.
4. Select a starting endpoint. This is the endpoint that you expect users to hit first in their request flow when using your API.  
   * Choose a hostname to display the list of endpoints for that hostname.  
   * Choose an endpoint.  
   * Select **Set as starting endpoint**.
5. Select a final endpoint. This is the endpoint you are targeting for protection.  
   * Choose a hostname to display the list of endpoints for that hostname.  
   * Choose an endpoint.  
   * Select **Set as ending endpoint**.
6. Choose an action that corresponds to the security model type:  
   * **Allow**: This will create a positive security model by defining approved sequences on your API.  
   * **Log** / **Block**: This will test or enforce a negative security model defining known bad sequences on your API.  
   Note  
   If you chose **Allow**, select whether to log or block the request to the final endpoint when users do not first request the starting endpoint in the sequence.
7. Select **Create rule**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Go to **Security** \> **API Shield** \> **API Rules**.
3. Select **Create sequence rule**.
4. Name your rule.
5. Select a starting endpoint. This is the endpoint that you expect users to hit first in their request flow when using your API.  
   * Choose a hostname to display the list of endpoints for that hostname.  
   * Choose an endpoint.  
   * Select **Set as starting endpoint**.
6. Select a final endpoint. This is the endpoint you are targeting for protection.  
   * Choose a hostname to display the list of endpoints for that hostname.  
   * Choose an endpoint.  
   * Select **Set as ending endpoint**.
7. Choose an action that corresponds to the security model type:  
   * **Allow**: This will create a positive security model by defining approved sequences on your API.  
   * **Log** / **Block**: This will test or enforce a negative security model defining known bad sequences on your API.  
   Note  
   If you chose **Allow**, select whether to log or block the request to the final endpoint when users do not first request the starting endpoint in the sequence.
8. Select **Create rule**.

## Edit a sequence rule

You also have the option to edit an existing rule by selecting it on the rule list. You can rename your rule, adjust the starting and ending endpoint order, modify the endpoint, and change the action of the rule.

## Reprioritize a sequence rule

You can change the priority order of your rules by selecting and dragging the rules on the list.

You can also explicitly set a priority order by selecting the three dots on your rule and choosing **Move to…** where you can set the new priority in the resulting modal window.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/sequence-mitigation/","name":"Sequence mitigation"}},{"@type":"ListItem","position":5,"item":{"@id":"/api-shield/security/sequence-mitigation/manage-sequence-rules/","name":"Manage sequence rules"}}]}
```

---

---
title: Volumetric Abuse Detection
description: Cloudflare Volumetric Abuse Detection helps you set up a system of adaptive rate limiting.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/volumetric-abuse-detection.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Volumetric Abuse Detection

Cloudflare Volumetric Abuse Detection helps you set up a system of adaptive rate limiting.

Cloudflare looks for endpoint abuse based on user traffic to individual endpoints.

For example, your API might see different levels of traffic to a `/reset-password` endpoint than a `/login` endpoint. Additionally, your `/login` endpoint might see higher than average traffic after a successful marketing campaign.

These two scenarios speak to the limitations of traditional rate limiting. Not only does traffic vary between endpoints, but it also can vary over time for the same endpoint. Volumetric Abuse Detection solves these problems with unsupervised learning to develop separate baselines for each API and better adjust to changes in user behavior.

Volumetric Abuse Detection rate limits are generated on a per-session basis. Unlike traditional rate limits, which are based on IP addresses, Volumetric Abuse Detection rate limits are not as susceptible to false positives when traffic to your API increases.

Volumetric Abuse Detection rate limits are a way to prevent blatant volumetric abuse while minimizing false positives. If you are trying to prevent abusive bot traffic altogether, refer to Cloudflare’s [Bot solutions](https://developers.cloudflare.com/bots/).

## Process

Volumetric Abuse Detection analyzes your API's individual session traffic statistics to recommend per-endpoint, per-session rate limits.

To access your endpoints:

Old dashboard: **Security** \> **API Shield** \> **Endpoint Management**

New dashboard: **Security** \> **Web Assets** \> **Endpoints**

Recommendations will continue to update if your traffic pattern changes.

### Requirements

Volumetric Abuse Detection generates rate limit thresholds only after collecting sufficient, statistically safe traffic data for an endpoint. If recommendations are missing for a discovered endpoint, the traffic likely failed to meet the necessary criteria.

Thresholds are suggested only for endpoints that satisfy all of the following requirements within the last seven days (or since initial discovery):

* The endpoint must receive sufficient valid traffic (traffic that meets the [API Discovery](https://developers.cloudflare.com/api-shield/security/api-discovery/#requirements) criteria). Intermittent or erratic traffic may prevent suggestions.
* The endpoint must be accessed by at least 50 distinct sessions in any 24-hour period during the last seven days.
* [Session identifiers](https://developers.cloudflare.com/api-shield/get-started/#to-set-up-session-identifiers), such as an authorization token available as a request header or cookie, must be configured to allow Cloudflare to accurately detect individual sessions and perform the required per-session rate analysis.

After adding a session identifier, allow 24 hours for rate limit recommendations to appear on endpoints in the Cloudflare dashboard.

### Rate limiting recommendation calculation

Once rate limit recommendations appear in **Endpoints**, select the endpoint row to view more detail about the recommendation. You will see the overall recommended rate limit value, as well as p99, p90, and p50 rate limit values.

We calculate the recommended rate limit value throughout the day, and the new calculation may equal the existing recommendation due to similar traffic profiles existing on your API. When we recalculate, we look at requests that happened in the last 24 hours.

Cloudflare recommends choosing the overall rate limit recommendation, as our analysis includes the variance of the request rate distribution across your API sessions. Choosing a single p-value may cause false positives due to a high number of outliers.

p-values

p-values describe what percentile of your traffic fits below the value. For example, if your p90 value is `83`, then 90% of your sessions had maximum request rates less than 83 requests per 10 minutes.

In **Endpoints**, you can review our confidence in the recommendation and how many unique sessions we have seen over the last seven (7) days. In general, endpoints with fewer unique sessions and high variability of user behavior will have lower confidence scores.

Implementing low confidence rate limits can still be helpful to prevent API abuse. If you are hesitant due to the recommendation’s confidence, we suggest starting your rate limit rule in `log` mode and observing violations of the rule for false positives.

### Create rate limits

Refer to the [Rules documentation ↗](https://developers.cloudflare.com/waf/rate-limiting-rules/create-zone-dashboard/) for more information on how to create an Advanced Rate Limiting rule.

## API

[Rate limit recommendations are available via the API](https://developers.cloudflare.com/api/resources/api%5Fgateway/subresources/operations/methods/get/) if you would like to dynamically update rate limits over time.

Required API token permissions

At least one of the following [token permissions](https://developers.cloudflare.com/fundamentals/api/reference/permissions/)is required:
* `Account API Gateway`
* `Account API Gateway Read`
* `Domain API Gateway`
* `Domain API Gateway Read`

Retrieve information about an operation

```

curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/api_gateway/operations/$OPERATION_ID" \

  --request GET \

  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"


```

## Special cases

### Rate limit by user (JWT claim)

You can rate limit requests based on any claim inside of a JSON Web Token (JWT), such as:

* Registered claims like `aud` or `sub`
* Custom claims like `userEmail`, including nested custom claims like `user.email`

Rate limiting based on JWT claim values will only work on valid JSON Web Tokens. If you do not block invalid JSON Web Tokens on your path, the [JWT claims will all be counted and possibly blocked](https://developers.cloudflare.com/waf/rate-limiting-rules/parameters/#missing-field-versus-empty-value) if high traffic is detected in the Point of Presence (PoP).

You must also count the JWT claim that uniquely identifies the user. If you select a claim that is the same for many of your users, their rate limits will all be counted together.

### Rate limit by user tier

If you offer multiple tiers on your website or application and you want to enforce rate limiting based on the tiers, such as:

* If `"aud": "free-tier"`, rate limit to five requests per minute.
* If `"aud": "premium-tier"`, rate limit to 50 requests per minute.

You can follow the rate limiting rule example below:

Example rule expression

```

(http.request.method eq "GET" and

http.host eq "<YOUR_DOMAIN>" and

http.request.uri.path matches "</EXAMPLE_PATH>" and

lookup_json_string(http.request.jwt.claims["<JWT_TOKEN_CONFIGURATION_ID>"][0], "aud") eq "free-tier"


```

## Limitations

API Shield will always calculate recommendations when session identifiers are configured. To enable session-based rate limits, [subscribe to Advanced Rate Limiting](https://developers.cloudflare.com/waf/rate-limiting-rules/#availability).

## Availability

Volumetric Abuse Detection is only available for Enterprise customers. If you are an Enterprise customer interested in this product, contact your account team.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/volumetric-abuse-detection/","name":"Volumetric Abuse Detection"}}]}
```

---

---
title: Configure Vulnerability Scanner via the API
description: Use Cloudflare Vulnerability Scanner to test your API endpoints for vulnerabilities such as Broken Object Level Authorization (BOLA). This guide explains how to run your first vulnerability scan using the Cloudflare API.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/security/vulnerability-scanner.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Configure Vulnerability Scanner via the API

Use Cloudflare Vulnerability Scanner to test your API endpoints for vulnerabilities such as Broken Object Level Authorization (BOLA). This guide explains how to run your first vulnerability scan using the Cloudflare API.

## Prerequisites

You must have:

* At least one zone in the account.
* An OpenAPI schema describing the API you want to scan.
* API credentials for your target. The scanner needs to authenticate as different users to test for BOLA vulnerabilities.

---

## Process

### Create an API token

All API requests use the base URL `https://api.cloudflare.com/client/v4/` and authenticate with a `Bearer` token in the `Authorization` header.

[Create an API token](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/) in the Cloudflare dashboard with the following [permissions](https://developers.cloudflare.com/fundamentals/api/reference/permissions/) scoped to the target account: **Account** \> **API Gateway** \> **Edit**

Save your API token and Account Tag from your account's **Overview** page in the Cloudflare dashboard as environment variables to use in the following commands.

Terminal window

```

export CLOUDFLARE_API_TOKEN="<YOUR_API_TOKEN>"

export ACCOUNT_ID="<YOUR_ACCOUNT_ID>"


```

### Create a target environment

A target environment defines what the scanner should scan. Currently, the only supported target type is zone.

Find your Zone Tag on the zone's **Overview** page in the Cloudflare dashboard and export it.

Terminal window

```

export ZONE_TAG="<YOUR_ZONE_TAG>"


```

Use the following `POST` request to create the target environment.

cURL command

```

curl "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/vuln_scanner/target_environments" \

  --header "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \

  --header "Content-Type: application/json" \

  --data '{

    "name": "Production API",

    "description": "Main production zone for API scanning",

    "target": {

      "type": "zone",

      "zone_tag": "'"${ZONE_TAG}"'"

    }

  }'


```

Save the target environment ID from the response into a variable `TARGET_ENV_ID`.

(Optional) You can verify your target environment by making a `GET` request to the following URL.

```

https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/vuln_scanner/target_environments/${TARGET_ENV_ID}


```

### Create credential sets

Currently, the scanner supports a BOLA scan. This requires two sets of credentials:

* Owner: A legitimate user who owns the resources being tested.
* Attacker: A different legitimate user who should not have access to the owner's resources.

The scanner authenticates as both users and checks whether the attacker can access the owner's resources. Each set of credentials is organized into a credential set containing one or more credentials.

Use the following `POST` requests to create an Owner credential set and an Attacker credential set.

Owner credential set

```

curl "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/vuln_scanner/credential_sets" \

  --header "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \

  --header "Content-Type: application/json" \

  --data '{ "name": "Owner Credentials" }'


# Export the ID from the response

export OWNER_CRED_SET_ID="<OWNER_CRED_SET_ID>"


```

Attacker credential set

```

curl "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/vuln_scanner/credential_sets" \

  --header "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \

  --header "Content-Type: application/json" \

  --data '{ "name": "Attacker Credentials" }'


# Export the ID from the response

export ATTACKER_CRED_SET_ID="<ATTACKER_CRED_SET_ID>"


```

### Add credentials to each credential set

A credential describes a single authentication token or session value that the scanner attaches to its requests.

Note

The value field is `write-only` and is never returned by the API.

Use the following `POST` requests to add the owner and attacker's credentials to each set.

Owner's credential (Header)

```

curl "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/vuln_scanner/credential_sets/${OWNER_CRED_SET_ID}/credentials" \

  --header "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \

  --header "Content-Type: application/json" \

  --data '{

    "name": "Owner Bearer Token",

    "location": "header",

    "location_name": "authorization",

    "value": "Bearer eyJhbGciOiJSUzI1NiIs...owner-token"

  }'


```

Attacker's credential (Cookie)

```

curl "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/vuln_scanner/credential_sets/${ATTACKER_CRED_SET_ID}/credentials" \

  --header "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \

  --header "Content-Type: application/json" \

  --data '{

    "name": "Attacker Session Cookie",

    "location": "cookie",

    "location_name": "session_id",

    "value": "attacker-session-token-value"

  }'


```

(Optional) You can list all credentials in a set using a `GET` request to the following URL.

```

https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/vuln_scanner/credential_sets/<CRED_SET_ID>/credentials


```

### Start a scan

With your target environment and two credential sets ready, you can start a BOLA scan.

Ensure your OpenAPI schema is formatted as a string. For example, using `jq`.

Terminal window

```

OPEN_API_SCHEMA=$(jq -c . < openapi.json)


```

Use the following `POST` request to initiate the scan.

cURL command

```

curl "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/vuln_scanner/scans" \

  --header "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \

  --header "Content-Type: application/json" \

  --data "$(jq -n \

    --arg te_id "$TARGET_ENV_ID" \

    --arg schema "$OPEN_API_SCHEMA" \

    --arg owner "$OWNER_CRED_SET_ID" \

    --arg attacker "$ATTACKER_CRED_SET_ID" \

    '{

      target_environment_id: $te_id,

      scan_type: "bola",

      open_api: $schema,

      credential_sets: { owner: $owner, attacker: $attacker }

    }')"


```

Save the scan ID from the response.

Terminal window

```

export SCAN_ID="<SCAN_ID>"


```

You can check the status of your scan using a `GET` request.

cURL command

```

curl "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/vuln_scanner/scans/${SCAN_ID}" \

  --header "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}"


```

### Retrieve the scan report

Once a scan has status `completed`, a report is available containing detailed findings for the vulnerabilities tested.

cURL command

```

curl "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/vuln_scanner/scans/${SCAN_ID}" \

  --header "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}"


```

Note

When the scan has not yet completed, the API returns the result as `null`.

You may find it easier to summarize the report results with `jq`.

Terminal window

```

curl "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/vuln_scanner/scans/${SCAN_ID}" \

  --header "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" | jq '.result.report.report.tests[] | {test_verdict: .verdict, steps: [.steps | to_entries[] | {step: (.key + 1), method: .value.request.method, url: .value.request.url, role: .value.request.credential_set.role, status: (if .value.errors | length > 0 then "error" else "ok" end)}]}'


```

Adding the `jq` command will summarize the output. In the following example, the attacker successfully accessed the `DELETE` endpoint in step 3.

```

{

  "test_verdict": "warning",

  "steps": [

    {

      "step": 1,

      "method": "POST",

      "url": "https://api.example.com/v1/orders",

      "role": "owner",

      "status": "ok"

    },

    {

      "step": 2,

      "method": "GET",

      "url": "https://api.example.com/v1/orders",

      "role": "attacker",

      "status": "ok"

    },

    {

      "step": 3,

      "method": "DELETE",

      "url": "https://api.example.com/v1/orders/bdc64e8a-deec-4374-92c0-4fe91d1650bb",

      "role": "attacker",

      "status": "error"

    }

  ]

}


```

#### Example polling pattern

A common pattern is to poll the scan status until it completes, then fetch the report.

Example

```

while true; do

  STATUS=$(curl --silent \

    "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/vuln_scanner/scans/${SCAN_ID}" \

    --header "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" | jq -r '.result.status // empty')


  echo "Scan status: ${STATUS:-unknown}"


  case "$STATUS" in

    completed) echo "Scan finished. Fetching report..."; break ;;

    failed)    echo "Scan failed." >&2; exit 1 ;;

    *)         sleep 10 ;;

  esac

done


curl --silent \

"https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/vuln_scanner/scans/${SCAN_ID}/report" \

  --header "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" | jq .


```

---

## Limitations

During the open beta, if you have large OpenAPI specs, you may want to optimize your specs for the scanner.

The AI model used to build a plan for scanning your API has a 128k token context limit. This approximates to 40 to 60kB of file size on disk. If your schema is larger than this size, you may need to split your schema into smaller files.

Similarly, you may see more thorough scan results by creating individual OpenAPI files by semantic use case. For example, if your application supports account modification, social sharing, and personal favoriting, splitting your spec into multiple files per these use cases may show increased test coverage during the beta.

---

## Availability

The vulnerability scanner is currently only available for Enterprise API Shield customers. Cloudflare will add more scan types in the future and increase the availability of the scanner at that time.

---

## Reference

### Credential locations

When creating credentials, the `location` field determines where the scanner attaches the credential during requests.

| Location | location\_name      | Example use case                          |
| -------- | ------------------- | ----------------------------------------- |
| header   | An HTTP header name | Authorization header with a Bearer token. |
| cookie   | A cookie name       | session\_id cookie with a session token.  |

A credential set can contain multiple credentials. For example, an API that requires both a `Bearer` token in the `Authorization` header and a `CSRF` token in the `X-CSRF-Token` header would have two separate credentials configured in its set.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/security/","name":"Security"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/security/vulnerability-scanner/","name":"Configure Vulnerability Scanner via the API"}}]}
```

---

---
title: API Gateway
description: Cloudflare API Shield empowers you to use Cloudflare as your API Gateway, providing robust security features, streamlined management tools, and integration with the Cloudflare Developer Platform for building new APIs.​
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/api-gateway.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# API Gateway

Cloudflare API Shield empowers you to use Cloudflare as your API Gateway, providing robust security features, streamlined management tools, and integration with the Cloudflare Developer Platform for building new APIs.​

APIs are fundamental to modern applications but are increasingly targeted by malicious actors. Cloudflare API Shield offers a comprehensive solution to protect, manage, and build your APIs.

* **Enhanced security**: Implement robust runtime protection such as JWT validation, mutual TLS (mTLS) authentication, Schema validation, and protection against the [OWASP Top 10 API Security risks ↗](https://owasp.org/www-project-api-security/).
* **Efficient management and monitoring**: Utilize tools for endpoint management, analytics, and routing to streamline API operations. Highlight risks with Posture Management, and gain visibility with Security Analytics and Security Center Insights.
* **Integrated development**: Leverage the Cloudflare Developer Platform to build and deploy new APIs with ease, taking advantage of scalable infrastructure and a suite of developer tools.

## Cloudflare as your API Gateway

### API security features

* **Protection Against OWASP Top 10 API Security risks**: Mitigate common API vulnerabilities, including injection attacks and improper asset management.

### Management and Monitoring tools

* **[Endpoint management](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/)**: Gain visibility into your API endpoints, including discovery of shadow APIs and monitoring of active endpoints.
* **[Analytics and logging](https://developers.cloudflare.com/api-shield/security/sequence-analytics/)**: Access detailed analytics and logs to monitor API usage, performance, and security events.
* **[API Routing](https://developers.cloudflare.com/api-shield/management-and-monitoring/api-routing/)**: Optimize API performance and reliability with secure routing.
* **[Posture Management](https://developers.cloudflare.com/api-shield/security/authentication-posture/)**: Monitor API Authentication status and receive alerts for common API risks.

### Build APIs with Cloudflare’s Developer Platform

The [Cloudflare Developer Platform ↗](https://www.cloudflare.com/developer-platform/) offers a serverless execution environment, allowing you to build and deploy new APIs without the need to manage infrastructure. Its benefits include:

* **Global scalability**: Deploy your APIs across Cloudflare's extensive global network, ensuring low latency and high availability. ​
* **Integrated services**: Access a suite of services, including storage, databases, and AI tools, to enhance your API functionality.
* **Developer-friendly tools**: Utilize modern development tools and frameworks to streamline the API development process. ​

## Get started

To begin using Cloudflare API Shield, refer to our [Get started](https://developers.cloudflare.com/api-shield/get-started/) guide.

For detailed instructions and additional resources, refer to the Cloudflare [API Shield documentation](https://developers.cloudflare.com/api-shield/).

By integrating API security, management, and development into a single platform, Cloudflare API Shield provides a comprehensive solution to protect, manage, and build APIs.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/api-gateway/","name":"API Gateway"}}]}
```

---

---
title: Glossary
description: Review the definitions for terms used across Cloudflare's API Shield documentation.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/glossary.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Glossary

Review the definitions for terms used across Cloudflare's API Shield documentation.

| Term               | Definition                                                                                                                                                    |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| API call           | Also known as an API request. An API call is a message sent to a server asking an API to provide a service or information.                                    |
| API endpoint       | The API endpoint is the location where API calls or requests are fulfilled. API Shield defines endpoints as a host, method, and path tuple.                   |
| API schema         | The API schema defines which API requests are valid based on several request properties like target endpoint, path or query variable format, and HTTP method. |
| session identifier | A session identifier is a unique identifier that a website assigns to identify a specific user for the duration of their visit.                               |
| source endpoint    | The source endpoint is the endpoint managed by API Shield in Endpoint Management by its routing feature.                                                      |
| target endpoint    | The target endpoint is the ultimate destination that a request is sent to by API Shield's routing feature.                                                    |

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/glossary/","name":"Glossary"}}]}
```

---

---
title: Changelog
description: Two new fields are now available in the httpRequestsAdaptive and httpRequestsAdaptiveGroups GraphQL Analytics API datasets:
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/changelog.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Changelog

[ Subscribe to RSS ](https://developers.cloudflare.com/changelog/rss/api-shield.xml) 

## 2026-03-23

  
**Web Assets fields now available in GraphQL Analytics API**   

Two new fields are now available in the `httpRequestsAdaptive` and `httpRequestsAdaptiveGroups` [GraphQL Analytics API](https://developers.cloudflare.com/analytics/graphql-api/) datasets:

* `webAssetsOperationId` — the ID of the [saved endpoint](https://developers.cloudflare.com/api-shield/management-and-monitoring/) that matched the incoming request.
* `webAssetsLabelsManaged` — the [managed labels](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-labels/#managed-labels) mapped to the matched operation at the time of the request (for example, `cf-llm`, `cf-log-in`). At most 10 labels are returned per request.

Both fields are empty when no operation matched. `webAssetsLabelsManaged` is also empty when no managed labels are assigned to the matched operation.

These fields allow you to determine, per request, which Web Assets operation was matched and which managed labels were active. This is useful for troubleshooting downstream security detection verdicts — for example, understanding why [AI Security for Apps](https://developers.cloudflare.com/waf/detections/ai-security-for-apps/) did or did not flag a request.

Refer to [Endpoint labeling service](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-labels/#analytics) for GraphQL query examples.

## 2026-03-09

  
**New Vulnerability Scanner for API Shield**   

Introducing Cloudflare's Web and API Vulnerability Scanner (Open Beta)

Cloudflare is launching the [Open Beta of the **Web and API Vulnerability Scanner** ↗](https://blog.cloudflare.com/vulnerability-scanner) for all [API Shield](https://developers.cloudflare.com/api-shield/) customers. This new, stateful Dynamic Application Security Testing (DAST) platform helps teams proactively find logic flaws in their APIs.

The initial release focuses on detecting Broken Object Level Authorization (BOLA) vulnerabilities by building API call graphs to simulate attacker and owner contexts, then testing these contexts by sending real HTTP requests to your APIs.

The scanner is now available via the Cloudflare API. To scan, set up your target environment, owner and attacker credentials, and upload your OpenAPI file with response schemas. The scanner will be available in the Cloudflare dashboard in a future release.

**Access**: This feature is only available to API Shield subscribers via the Cloudflare API. We hope you will use the API for programmatic integration into your CI/CD pipelines and security dashboards.

**Documentation**: Refer to the [developer documentation](https://developers.cloudflare.com/api-shield/security/vulnerability-scanner/) to start scanning your endpoints today.

## 2025-11-12

  
**New BOLA Vulnerability Detection for API Shield**   

Now, API Shield automatically searches for and highlights **Broken Object Level Authorization (BOLA) attacks** on managed API endpoints. API Shield will highlight both BOLA enumeration attacks and BOLA pollution attacks, telling you what was attacked, by who, and for how long.

You can find these attacks three different ways: Security Overview, Endpoint details, or Security Analytics. If these attacks are not found on your managed API endpoints, there will not be an overview card or security analytics suspicious activity card.

![BOLA attack Overview card](https://developers.cloudflare.com/_astro/bola-overview-card.hwcSeAkb_1MwSDq.webp)![BOLA attack Overview drawer](https://developers.cloudflare.com/_astro/bola-overview-drawer.DD2c0bxS_zw6Ec.webp) 

From the endpoint details, you can select **View attack** to find details about the BOLA attacker’s sessions.

![BOLA attack endpoint details](https://developers.cloudflare.com/_astro/bola-endpoint-attack.UQP3MDkp_1Yhqqd.webp) 

From here, select **View in Analytics** to observe attacker traffic over time for the last seven days.

![BOLA attack analytics drawer](https://developers.cloudflare.com/_astro/bola-analytics-drawer.DXzC6EJU_iXjmr.webp) 

Your search will filter to traffic on that endpoint in the last seven days, along with the malicious session IDs found in the attack. Session IDs are hashed for privacy and will not be found in your origin logs. Refer to IP and JA4 fingerprint to cross-reference behavior at the origin.

At any time, you can also start your investigation into attack traffic from Security Analytics by selecting the suspicious activity card.

![Suspicious Activity card](https://developers.cloudflare.com/_astro/bola-suspicious-card._B3GB3s4_STW1N.webp) 

We urge you to take all of this client information to your developer team to research the attacker behavior and ensure any broken authorization policies in your API are fixed at the source in your application, preventing further abuse.

In addition, this release marks the end of the beta period for these scans. All Enterprise customers with API Shield subscriptions will see these new attacks if found on their zone.

## 2025-03-18

  
**New API Posture Management for API Shield**   

Now, API Shield **automatically** labels your API inventory with API-specific risks so that you can track and manage risks to your APIs.

View these risks in [Endpoint Management](https://developers.cloudflare.com/api-shield/management-and-monitoring/) by label:

![A list of endpoint management labels](https://developers.cloudflare.com/_astro/endpoint-management-label.BDmf8Ai1_ZM5mgU.webp) 

...or in [Security Center Insights](https://developers.cloudflare.com/security-center/security-insights/):

![An example security center insight](https://developers.cloudflare.com/_astro/posture-management-insight.7vB7mzGI_Z1HKoUN.webp) 

API Shield will scan for risks on your API inventory daily. Here are the new risks we're scanning for and automatically labelling:

* **cf-risk-sensitive**: applied if the customer is subscribed to the [sensitive data detection ruleset](https://developers.cloudflare.com/waf/managed-rules/reference/sensitive-data-detection/) and the WAF detects sensitive data returned on an endpoint in the last seven days.
* **cf-risk-missing-auth**: applied if the customer has configured a session ID and no successful requests to the endpoint contain the session ID.
* **cf-risk-mixed-auth**: applied if the customer has configured a session ID and some successful requests to the endpoint contain the session ID while some lack the session ID.
* **cf-risk-missing-schema**: added when a learned schema is available for an endpoint that has no active schema.
* **cf-risk-error-anomaly**: added when an endpoint experiences a recent increase in response errors over the last 24 hours.
* **cf-risk-latency-anomaly**: added when an endpoint experiences a recent increase in response latency over the last 24 hours.
* **cf-risk-size-anomaly**: added when an endpoint experiences a spike in response body size over the last 24 hours.

In addition, API Shield has two new 'beta' scans for **Broken Object Level Authorization (BOLA) attacks**. If you're in the beta, you will see the following two labels when API Shield suspects an endpoint is suffering from a BOLA vulnerability:

* **cf-risk-bola-enumeration**: added when an endpoint experiences successful responses with drastic differences in the number of unique elements requested by different user sessions.
* **cf-risk-bola-pollution**: added when an endpoint experiences successful responses where parameters are found in multiple places in the request.

We are currently accepting more customers into our beta. Contact your account team if you are interested in BOLA attack detection for your API.

Refer to the [blog post ↗](https://blog.cloudflare.com/cloudflare-security-posture-management/) for more information about Cloudflare's expanded posture management capabilities.

## 2025-02-17

**New automatically applied risk labels**

API Shield now automatically labels endpoints with risks due to missing schemas and performance anomalies (spikes in error rates, latency, and body response sizes).

## 2025-01-16

**API Authentication Posture**

Customers will see per-endpoint authentication details inside [Endpoints](https://developers.cloudflare.com/api-shield/management-and-monitoring/) for zones with configured session identifiers.

## 2024-12-19

**Automatically applied endpoint risk labels**

API Shield now automatically labels endpoints with risks due to authentication status and sensitive data detection.

## 2024-11-04

**Endpoint labels**

Customers can now organize their endpoints by use case and custom labels using the [Endpoint labeling service](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-labels/) for easy reference and future machine learning (ML) model training.

## 2024-10-18

**API Shield fields in Custom Rules**

Customers can now use API Shield product feature fields in [custom rules](https://developers.cloudflare.com/waf/custom-rules/), referencing features such as [JWT validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/), [session identifiers](https://developers.cloudflare.com/api-shield/get-started/#session-identifiers), and [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/).

## 2024-09-25

**Fallthrough rule for Schema validation 2.0**

Customers can now enable the [Fallthrough Action](https://developers.cloudflare.com/api-shield/security/schema-validation/#add-validation-by-adding-a-fallthrough-rule) for Schema validation 2.0 to block or log requests that do not match the endpoints listed in schemas protected by Schema validation 2.0.

## 2024-08-28

**Increased capacity for Endpoint management and Schema validation**

Endpoint management and Schema validation now support up to 10,000 saved and validated API endpoints.

## 2024-07-08

**API Discovery's hostname variables**

Customers can now see when [API Discovery](https://developers.cloudflare.com/api-shield/security/api-discovery/) groups similar subdomains with the same methods and paths, making it easy to discover and manage APIs that share many vanity domains or subdomains.

## 2024-07-02

**Route API requests using API Routing**

Customers can now route requests to different back-end services through [API Routing](https://developers.cloudflare.com/api-shield/management-and-monitoring/api-routing/), creating a unified front for their APIs distributed across otherwise disparate systems.

## 2024-05-13

**Use JWT claims in Advanced Rate Limiting, Transform Rules, and as session IDs**

Customers can now use the fields inside [JSON Web Tokens (known as claims)](https://developers.cloudflare.com/api-shield/security/jwt-validation/transform-rules/#enhance-transform-rules-with-jwt-claims) as [session identifiers in API Shield](https://developers.cloudflare.com/api-shield/get-started/#session-identifiers), to count values in [Advanced Rate Limiting](https://developers.cloudflare.com/waf/rate-limiting-rules/), and to send on useful information in [Transform Rules](https://developers.cloudflare.com/rules/transform/).

## 2024-04-30

**Build sequence mitigation rules via the Cloudflare dashboard**

Customers can now build [Sequence mitigation](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/) rules with a new user interface inside the API Shield section of the [Cloudflare dashboard ↗](https://dash.cloudflare.com/).

## 2024-02-23

**Endpoint management supports hostname variables**

Customers can now save endpoints in [Endpoint management](https://developers.cloudflare.com/api-shield/management-and-monitoring/) that contain variables in the hostname. Hostname variables are supported across all product features.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/changelog/","name":"Changelog"}}]}
```

---

---
title: API Routing
description: API Shield Routing enables customers to create a unified external-facing API that routes requests to different back-end services that may have different paths and hosts than the existing zone and DNS configuration.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/management-and-monitoring/api-routing.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# API Routing

API Shield Routing enables customers to create a unified external-facing API that routes requests to different back-end services that may have different paths and hosts than the existing zone and DNS configuration.

Note

The term **Source Endpoint** refers to the endpoint managed by API Shield in Endpoint Management. The term **Target Endpoint** refers to the ultimate destination the request is sent to by the Routing feature.

## Process

You must add Source Endpoints to Endpoint Management through established methods, including [uploading a schema](https://developers.cloudflare.com/api-shield/security/schema-validation/#add-validation-by-uploading-a-schema), via [API Discovery](https://developers.cloudflare.com/api-shield/security/api-discovery/), or by [adding manually](https://developers.cloudflare.com/api-shield/management-and-monitoring/#add-endpoints-manually), before creating a route.

To create a route, you will need the operation ID of the Source Endpoint. To find the operation ID in the dashboard:

* [  New dashboard ](#tab-panel-3128)
* [ Old dashboard ](#tab-panel-3129)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Filter the endpoints to find your **Source Endpoint**.
3. Expand the row for your Source Endpoint and note the **operation ID** field.
4. Select the copy icon to copy the operation ID to your clipboard.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Select **Security** \> **API Shield**.
3. Filter the endpoints to find your **Source Endpoint**.
4. Expand the row for your Source Endpoint and note the **operation ID** field.
5. Select the copy icon to copy the operation ID to your clipboard.

Once your Source Endpoints are added to Endpoint Management, use the following steps to create and verify routes on any given operation ID:

### Create a route

* [  New dashboard ](#tab-panel-3130)
* [ Old dashboard ](#tab-panel-3131)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. In **Endpoints**, select an existing endpoint and expand its details.
3. Under **Routing**, select **Create route**.
4. Enter the target URL or IP address to route your endpoint to.
5. Select **Deploy route**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Go to **Security** \> **API Shield**.
3. In **Endpoint Management**, select an existing endpoint and expand its details.
4. Under **Routing**, select **Create route**.
5. Enter the target URL or IP address to route your endpoint to.
6. Select **Deploy route**.

Note

You can reorder path variables if they are present. For example, you can route `/api/{var1}/users/{var2}` to `/{var2}/users/{var1}`. Segments of the path that are not variables may be added or omitted entirely.

You can also edit or delete a route by selecting **Edit route** on an existing route.

### Test a route

After sending a request to your Source Endpoint, you should see the contents of the back-end service as if you called the Target Endpoint directly.

If API Shield returns unexpected results, check your Source Endpoint host, method, and path and [verify the Route](https://developers.cloudflare.com/api-shield/management-and-monitoring/api-routing/#verify-a-route) to ensure the Target Endpoint value is correct.

Note

You may need to wait up to five minutes for Route changes to synchronize across the Cloudflare network.

## Availability

API Shield Routing is currently in an open beta and is only available for Enterprise customers subscribed to API Shield. Enterprise customers who have not purchased API Shield can preview [API Shield as a non-contract service ↗](https://dash.cloudflare.com/?to=/:account/:zone/security/api-shield) in the Cloudflare dashboard or by contacting your account team.

## Limitations

The Target Endpoint cannot be routed to a Worker if the route is to the same zone.

You cannot change the method of a request. For example, a `GET` Source Endpoint will always send a `GET` request to the Target Endpoint.

You must use all of the variables in the Target Endpoint that appear in the Source Endpoint. For example, routing `/api/{var1}/users/{var2}` to `/api/users/{var2}` is not allowed and will result in an error since `{var1}` is present in the Source Endpoint but not in the Target Endpoint.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/management-and-monitoring/","name":"Management and Monitoring"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/management-and-monitoring/api-routing/","name":"API Routing"}}]}
```

---

---
title: Build developer portals
description: Once your endpoints are saved, API Shield doubles as an API catalog. API Shield can build an interactive documentation portal with the knowledge it has of your APIs, or you can upload a new OpenAPI schema file to build a documentation portal ad-hoc.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/management-and-monitoring/developer-portal.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Build developer portals

Once your endpoints are saved, API Shield doubles as an API catalog. API Shield can build an interactive documentation portal with the knowledge it has of your APIs, or you can upload a new OpenAPI schema file to build a documentation portal ad-hoc.

To create a developer portal:

* [  New dashboard ](#tab-panel-3132)
* [ Old dashboard ](#tab-panel-3133)

1. In the Cloudflare dashboard, go to the **Security Settings** page.  
[ Go to **Settings** ](https://dash.cloudflare.com/?to=/:account/:zone/security/settings)
2. Filter by **API abuse**.
3. On **Create a developer portal**, select **Create site**.
4. Upload an OpenAPI v3.0 schema file or choose to select an existing schema from API Shield.  
Note  
If you do not have a schema to upload or to select from a pre-existing schema, export your Endpoint Management schema. For best results, include the learned parameters.  
Only API schemas uploaded to Schema validation 2.0 are available when selecting existing schemas.
5. Select **Download project files** to save a local copy of the files that will be uploaded to Cloudflare Pages. Downloading the project files can be helpful if you wish to modify the project in any way and then upload the new version manually to Pages.
6. Select **Create pages project** to begin project creation. A new Pages project will be automatically created and your API schema will be automatically uploaded to the project along with other supporting static content.
7. Select **Deploy site**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Go to **Security** \> **API Shield** \> **Settings**.
3. Under **Create a developer portal**, select **Create site**.
4. Upload an OpenAPI v3.0 schema file or choose to select an existing schema from API Shield.  
Note  
If you do not have a schema to upload or to select from a pre-existing schema, export your Endpoint Management schema. For best results, include the learned parameters.  
Only API schemas uploaded to Schema validation 2.0 are available when selecting existing schemas.
5. Select **Download project files** to save a local copy of the files that will be uploaded to Cloudflare Pages. Downloading the project files can be helpful if you wish to modify the project in any way and then upload the new version manually to Pages.
6. Select **Create pages project** to begin project creation. A new Pages project will be automatically created and your API schema will be automatically uploaded to the project along with other supporting static content.
7. Select **Deploy site**.

### Custom domains

To create a vanity domain instead of using the pages.dev domain, refer to the [Pages custom domain documentation](https://developers.cloudflare.com/pages/configuration/custom-domains/).

## Availability

Building developer portals is available to all API Shield subscribers. This feature uses Cloudflare Pages to host the resulting portal. Refer to [Pages](https://developers.cloudflare.com/pages/) for any limitations of your current subscription plan.

## Limitations

This feature currently uses the open source [Redoc ↗](https://github.com/Redocly/redoc) project from [Redocly ↗](https://redocly.com/). For custom theme and branding options, visit the [Redoc GitHub repository ↗](https://github.com/Redocly/redoc).

To modify the resulting page, download the project files before creating the Pages project. You can create a new Pages project with the modified files you have made to meet your branding guidelines.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/management-and-monitoring/","name":"Management and Monitoring"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/management-and-monitoring/developer-portal/","name":"Build developer portals"}}]}
```

---

---
title: Endpoint labeling service
description: API Shield's labeling service will help you organize your endpoints and address vulnerabilities in your API. The labeling service comes with managed and user-defined labels.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/management-and-monitoring/endpoint-labels.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Endpoint labeling service

API Shield's labeling service will help you organize your endpoints and address vulnerabilities in your API. The labeling service comes with managed and user-defined labels.

Today, managed labels are useful for organizing endpoints by use case. In a future release, managed labels will automatically label endpoints by use case and those with informative or security risks, alerting you on endpoints that need attention.

User-defined labels can also be added to endpoints in API Shield by creating a label and adding it to an individual endpoint or multiple endpoints. User-defined labels will be useful for organizing your endpoints by owner, version, or type.

You can filter your endpoints based on the labels.

## Categories

### Managed labels

Use managed labels to identify endpoints by use case. Cloudflare may automatically apply these labels in a future release.

`cf-log-in`: Add this label to endpoints that accept user credentials. You may have multiple endpoints if you accept username, password, and multi-factor authentication (MFA) across multiple endpoints or requests.

`cf-sign-up`: Add this label to endpoints that are the final step in creating user accounts for your site or application.

`cf-content`: Add this label to endpoints that provide unique content, such as product details, user reviews, pricing, or other unique information.

`cf-purchase`: Add this label to endpoints that are the final step in purchasing goods or services online.

`cf-password-reset`: Add this label to endpoints that participate in the user password reset process. This includes initial password reset requests and final password reset submissions.

`cf-add-cart`: Add this label to endpoints that add items to a user's shopping cart or verify item availability.

`cf-add-payment`: Add this label to endpoints that accept credit card or bank account details where fraudsters may iterate through account numbers to guess valid combinations of payment information.

`cf-check-value`: Add this label to endpoints that check the balance of rewards points, in-game currency, or other stored value products that can be earned, transferred, and redeemed for cash or physical goods.

`cf-add-post`: Add this label to endpoints that post messages in a communication forum, or product or merchant reviews.

`cf-account-update`: Add this label to endpoints that participate in user account or profile updates.

`cf-llm`: Services that are (partially) powered by Large Language Model (LLM).

`cf-rss-feed`: Add this label to endpoints that expect traffic from RSS clients.

`cf-web-page`: Add this label to endpoints that serve HTML pages.

Note

[Bot Fight Mode](https://developers.cloudflare.com/bots/get-started/bot-fight-mode/) will not block requests to endpoints labeled as `cf-rss-feed`.

[Super Bot Fight Mode rules](https://developers.cloudflare.com/bots/get-started/super-bot-fight-mode/#ruleset-engine) will not match or challenge requests labeled as `cf-rss-feed`.

### Risk labels

Cloudflare automatically runs risk scans every 24 hours on your saved endpoints. API Shield applies these labels when a scan finds security risks on your endpoints. A corresponding Security Center Insight is also raised when risks are found.

`cf-risk-missing-auth`: Automatically added when all successful requests lack a session identifier. Refer to [Authentication Posture](https://developers.cloudflare.com/api-shield/security/authentication-posture/#process) for more information.

`cf-risk-mixed-auth`: Automatically added when some successful requests contain a session identifier and some successful requests lack a session identifier. Refer to [Authentication Posture](https://developers.cloudflare.com/api-shield/security/authentication-posture/#process) for more information.

`cf-risk-sensitive`: Automatically added to endpoints when HTTP responses match the WAF's [Sensitive Data Detection](https://developers.cloudflare.com/api-shield/management-and-monitoring/#sensitive-data-detection) ruleset.

`cf-risk-missing-schema`: Automatically added when a learned schema is available for an endpoint that has no active schema.

`cf-risk-error-anomaly`: Automatically added when an endpoint experiences a recent increase in response errors over the last 24 hours.

`cf-risk-latency-anomaly`: Automatically added when an endpoint experiences a recent increase in response latency over the last 24 hours.

`cf-risk-size-anomaly`: Automatically added when an endpoint experiences a spike in response body size over the last 24 hours.

`cf-risk-bola-enumeration`: Automatically added when an endpoint experiences successful responses with drastic differences in the number of unique elements requested by different user sessions.

`cf-risk-bola-pollution`: Automatically added when an endpoint experiences successful responses where parameters are found in multiple places in the request, as opposed to what is expected from the API's schema.

Note

Cloudflare will only add authentication labels to endpoints with successful response codes. Refer to the below table for more details.

#### Recommended action

How you address risks to your endpoints will depend on its label(s). The following steps provide you with general guidelines on how to take action on them.

1. Review risks to endpoints.  
View the endpoints labeled as risks and identify if they have been labeled for other risks.  
For example, endpoints labeled `cf-risk-sensitive` and `cf-risk-missing-auth` or `cf-risk-mixed-auth` may contain sensitive data that is available to unauthenticated users.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)  
Go to the details pages for endpoints labeled as `cf-risk-missing-auth` or `cf-risk-mixed-auth`, and check for recent changes in the authenticated traffic profile in the last 24 hours and seven days.
2. Review traffic to these labeled endpoints in Security Analytics.  
Check for unexpected traffic sources and note any irregular traffic patterns.  
Filtering  
Filtering by risk label includes all traffic to all endpoints labeled with that risk, not only the traffic that prompted Cloudflare to apply the label.  
[ Go to **Analytics** ](https://dash.cloudflare.com/?to=/:account/:zone/security/analytics)
3. Review your origin's authorization and authentication policies with your development team.  
Speak with your developers or application owners in your organization to understand whether or not all requests to these endpoints should be authenticated. Modify your application to consistently enforce the authentication requirement for all traffic accessing these endpoints.  
Refer to [Authentication Posture](https://developers.cloudflare.com/api-shield/security/authentication-posture/) for more information.

---

## Analytics

### GraphQL Analytics API

You can query the matched operation and managed labels for individual requests using the [GraphQL Analytics API](https://developers.cloudflare.com/analytics/graphql-api/). The `webAssetsOperationId` and `webAssetsLabelsManaged` fields are available in the `httpRequestsAdaptive` and `httpRequestsAdaptiveGroups` datasets. Use [introspection](https://developers.cloudflare.com/analytics/graphql-api/features/discovery/introspection/) to explore the full schema and available filter operators.

`webAssetsLabelsManaged` returns at most 10 labels per request.

#### Example: query requests by managed label

The following query returns the count of requests per operation ID and managed label set, filtered to requests where the matched operation carries the `cf-log-in` managed label.

```

query GetAdaptiveGroups($start: DateTime!, $end: DateTime!) {

  viewer {

    zones(filter: { zoneTag: $zoneTag }) {

      httpRequestsAdaptiveGroups(

        filter: {

          datetime_geq: $start

          datetime_leq: $end

          requestSource: "eyeball"

          webAssetsLabelsManaged_hasany: ["cf-log-in"]

        }

        limit: 25

        orderBy: [count_DESC]

      ) {

        count

        dimensions {

          webAssetsOperationId

          webAssetsLabelsManaged

        }

      }

    }

  }

}


```

Replace `cf-log-in` with any [managed label](#managed-labels) or [risk label](#risk-labels). You can also omit the `webAssetsLabelsManaged_hasany` filter and use `webAssetsOperationId` as the sole dimension to group traffic by matched operation regardless of label.

### Logpush

You can export per-request Web Assets data to your storage or SIEM system of choice using [Logpush](https://developers.cloudflare.com/logs/logpush/). The `WebAssetsOperationID` and `WebAssetsLabelsManaged` fields are available in the [HTTP requests dataset](https://developers.cloudflare.com/logs/logpush/logpush-job/datasets/zone/http%5Frequests/#webassetslabelsmanaged).

---

## Create a label

* [  New dashboard ](#tab-panel-3136)
* [ Old dashboard ](#tab-panel-3137)

1. In the Cloudflare dashboard, go to the **Security Settings** page.  
[ Go to **Settings** ](https://dash.cloudflare.com/?to=/:account/:zone/security/settings)
2. Filter by **API abuse**.
3. Under **Endpoint labels**, select **Manage labels**.
4. Name the label and add an optional label description.
5. Apply the label to your selected endpoints.
6. Select **Create label**.

Alternatively, you can create a user-defined label via **Security** \> **Web Assets**.

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Go to the **Endpoints** tab.
3. Choose the endpoint that you want to label.
4. Select **Edit endpoint labels**.
5. Under **User**, select **Create user label**.
6. Enter the label name.
7. Select **Create**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Go to **Security** \> **Settings** \> **Labels**.
3. Under **Security labels**, select **Create label**.
4. Name the label and add an optional label description.
5. Apply the label to your selected endpoints.
6. Select **Create label**.

Alternatively, you can create a user-defined label via Endpoint Management in API Shield:

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Go to **Security** \> **Settings** \> **Labels**.
3. Choose the endpoint that you want to label.
4. Select **Edit labels**.
5. Under **User**, select **Create user label**.
6. Enter the label name.
7. Select **Create**.

## Apply a label to an individual endpoint

* [  New dashboard ](#tab-panel-3138)
* [ Old dashboard ](#tab-panel-3139)

1. In the Cloudflare dashboard, go to the **Web assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. In the **Endpoints** tab, choose the endpoint that you want to label.
3. Select **Edit endpoint labels**.
4. Add the label(s) that you want to use for the endpoint from the list of managed and user-defined labels.
5. Select **Save labels**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Go to **Security** \> **API Shield**.
3. In the **Endpoint Management** tab, choose the endpoint that you want to label.
4. Select **Edit labels**.
5. Add the label(s) that you want to use for the endpoint from the list of managed and user-defined labels.
6. Select **Save labels**.

## Bulk apply labels to multiple endpoints

* [  New dashboard ](#tab-panel-3134)
* [ Old dashboard ](#tab-panel-3135)

1. In the Cloudflare dashboard, go to the **Security Settings** page.  
[ Go to **Settings** ](https://dash.cloudflare.com/?to=/:account/:zone/security/settings)
2. Filter by **API abuse**.
3. On **Endpoint labels**, select **Manage labels**.
4. On the existing label that you want to apply to multiple endpoints, select **Bulk apply**.
5. Choose the endpoints that you want to label by selecting its checkbox.
6. Select **Apply label**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Go to **Security** \> **Settings** \> **Labels**.
3. On the existing label that you want to apply to multiple endpoints, select **Bulk apply**.
4. Choose the endpoints that you want to label by selecting its checkbox.
5. Select **Save label**.

## Availability

Endpoint labeling is available to all customers.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/management-and-monitoring/","name":"Management and Monitoring"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/management-and-monitoring/endpoint-labels/","name":"Endpoint labeling service"}}]}
```

---

---
title: Endpoint Management
description: Monitor the health of your API endpoints by saving, updating, and monitoring performance metrics using API Shield’s Endpoint Management.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/management-and-monitoring/endpoint-management/index.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Endpoint Management

 Available on all plans 

Monitor the health of your API endpoints by saving, updating, and monitoring performance metrics using API Shield’s Endpoint Management.

**Add endpoints** allows customers to save endpoints directly from [API Discovery](https://developers.cloudflare.com/api-shield/security/api-discovery/) or manually by method, path, and host.

This will add the specified endpoints to your list of managed endpoints. You can view your list of saved endpoints in the **Endpoint Management** page.

Cloudflare will start collecting [performance data](https://developers.cloudflare.com/api-shield/management-and-monitoring/#endpoint-analysis) on your endpoint when you save an endpoint.

Note

When an endpoint is using [Cloudflare Workers](https://developers.cloudflare.com/workers/), the metrics data will not be populated.

## Access

* [  New dashboard ](#tab-panel-3150)
* [ Old dashboard ](#tab-panel-3151)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Go to the **Endpoints** tab.
3. Select **Add endpoints**.
4. Add your endpoints [manually](#add-endpoints-manually), from [Schema validation](#add-endpoints-from-schema-validation), or from [API Discovery](#add-endpoints-from-api-discovery).

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/login), and select your account and domain.
2. Select **Security** \> **API Shield**.
3. Add your endpoints [manually](#add-endpoints-manually), from [Schema validation](#add-endpoints-from-schema-validation), or from [API Discovery](#add-endpoints-from-api-discovery).

### Add endpoints from API Discovery

There are two ways to add API endpoints from Discovery.

#### Add from the Endpoints tab

* [  New dashboard ](#tab-panel-3140)
* [ Old dashboard ](#tab-panel-3141)

1. From **Endpoints**, go to **Add endpoints** \> **Select from Discovery** tab.
2. Select the discovered endpoints you would like to add.
3. Select **Add endpoints**.

1. From **Endpoint Management**, select **Add endpoints** \> **Select from Discovery** tab.
2. Select the discovered endpoints you would like to add.
3. Select **Add endpoints**.

#### Add from the Discovery tab

* [  New dashboard ](#tab-panel-3142)
* [ Old dashboard ](#tab-panel-3143)

1. From **Web assets**, go to the **Discovery** tab.
2. Select the discovered endpoints you would like to add.
3. Select **Save selected endpoints**.

1. From Endpoint Management, select the **Discovery** tab.
2. Select the discovered endpoints you would like to add.
3. Select **Save selected endpoints**.

### Add endpoints from Schema validation

* [  New dashboard ](#tab-panel-3144)
* [ Old dashboard ](#tab-panel-3145)

1. From **Web assets**, go to the **Endpoints** tab.
2. Select **Add endpoints** \> **Upload Schema**.
3. Upload a schema file.
4. Select **Add schema and endpoints**.

1. Add a schema by [configuring Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/).
2. On **Review schema endpoints**, save new endpoints to endpoint management by checking the box.
3. Select **Save as draft** or **Save and Deploy**. Endpoints will be saved regardless of whether the schema is saved as a draft or published.

API Shield will look for duplicate endpoints that have the same host, method, and path. Duplicate endpoints will not be saved to endpoint management.

Note

If you deselect **Save new endpoints to endpoint management**, the endpoints will not be added.

### Add endpoints manually

* [  New dashboard ](#tab-panel-3146)
* [ Old dashboard ](#tab-panel-3147)

1. From **Web assets**, go to the **Endpoints** tab.
2. Select **Add endpoints** \> **Manually add**.
3. Choose the method from the dropdown menu and add the path and hostname for the endpoint.
4. Select **Add endpoints**.

1. From Endpoint Management, select **Add endpoints** \> **Manually add**.
2. Choose the method from the dropdown menu and add the path and hostname for the endpoint.
3. Select **Add endpoints**.

Note

By selecting multiple checkboxes, you can add several endpoints from Discovery at once instead of individually.

When adding an endpoint manually, you can specify variable fields in the path or host by enclosing them in braces, `/api/user/{var1}/details` or `{hostVar1}.example.com`.

Cloudflare supports hostname variables in the following formats:

```

{hostVar1}.example.com


foo.{hostVar1}.example.com


{hostVar2}.{hostVar1}.example.com


```

Hostname variables must comprise the entire domain field and must not be used with other text in the field.

The following format is not supported:

```

foo-{hostVar1}.example.com


```

For more information on how Cloudflare uses variables in API Shield, refer to the examples from [API Discovery](https://developers.cloudflare.com/api-shield/security/api-discovery/).

### Delete endpoints manually

You can delete endpoints one at a time or in bulk.

* [  New dashboard ](#tab-panel-3148)
* [ Old dashboard ](#tab-panel-3149)

1. From **Web assets**, go to the **Endpoints** tab.
2. Select the checkboxes for the endpoints that you want to delete.
3. Select **Delete endpoints**.

1. From Endpoint Management, select the checkboxes for the endpoints that you want to delete.
2. Select **Delete endpoints**.

Warning

When you delete an endpoint from Endpoint Management, Cloudflare immediately stops tracking all associated performance and analytics data. The endpoint's previous historical metrics are permanently removed and cannot be restored. If you later save this endpoint again, metric tracking will resume, starting from the point the endpoint is re-saved.

## Endpoint Analysis

For each saved endpoint, customers can view:

* **Request count**: The total number of requests to the endpoint over time.
* **Rate limiting recommendation**: per 10 minutes. This is guided by the request count.
* **Latency**: The average origin response time in milliseconds (ms). This metric shows how long it takes from the moment a visitor makes a request to the moment the visitor gets a response back from the origin.
* **Error rate** vs. overall traffic: grouped by 4xx, 5xx, and their sum.
* **Response size**: The average size of the response (in bytes) returned to the request.
* **Labels**: The current [labels](https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-labels/) assigned to the endpoint.
* **[Authentication status](https://developers.cloudflare.com/api-shield/security/authentication-posture/)**: The breakdown of which [session identifiers](https://developers.cloudflare.com/api-shield/get-started/#session-identifiers) were seen on successful requests to this endpoint.
* **Sequences**: The number of [Sequence Analytics](https://developers.cloudflare.com/api-shield/security/sequence-analytics/) sequences the endpoint was found in.

Note

Customers viewing analytics have the ability to toggle detailed metrics view between the last 24 hours and 7 days.

## Using the Cloudflare API

You can interact with Endpoint Management through the Cloudflare API. Refer to [Endpoint Management’s API documentation](https://developers.cloudflare.com/api/resources/api%5Fgateway/subresources/discovery/subresources/operations/methods/list/) for more information.

## Sensitive Data Detection

Sensitive data comprises various personally identifiable information and financial data. Cloudflare created this ruleset to address common data loss threats, and the WAF can search for this data in HTTP response bodies from your origin.

API Shield will alert users to the presence of sensitive data in the response body of API endpoints listed in Endpoint Management if the zone is also subscribed to the [Sensitive Data Detection managed ruleset](https://developers.cloudflare.com/waf/managed-rules/reference/sensitive-data-detection/).

Sensitive Data Detection is available to Enterprise customers on our Advanced application security plan.

Once Sensitive Data Detection is enabled for your zone, API Shield queries firewall events from the WAF for the last seven days and places a notification icon on the Endpoint Management table row if there are any matched sensitive responses for your endpoint.

API Shield displays the types of sensitive data found if you expand the Endpoint Management table row to view further details. Select **Explore Events** to view the matched events in Security Events.

After Sensitive Data Detection is enabled for your zone, you can [browse the Sensitive Data Detection ruleset ↗](https://dash.cloudflare.com/?to=/:account/:zone/security/data/ruleset/e22d83c647c64a3eae91b71b499d988e/rules). The link will not work if Sensitive Data Detection is not enabled.

## Limitations

Certain performance metrics, such as latency, are not supported when a request is handled by a Cloudflare service in a way that prevents it from being passed directly to your origin server.

This limitation is specifically observed when:

* A Cloudflare Worker is running on the URL path.
* Other products built on top of Workers, such as [Waiting Room](https://developers.cloudflare.com/waiting-room/), are active on the application.

In these scenarios, the system is unable to accurately measure the origin response time, and the metric will not be populated in the dashboard.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/management-and-monitoring/","name":"Management and Monitoring"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/management-and-monitoring/endpoint-management/","name":"Endpoint Management"}}]}
```

---

---
title: Schema learning
description: Cloudflare learns schema parameters via traffic inspection. For all endpoints saved to Endpoint Management, you can export the learned schema in OpenAPI v3.0.0 format by hostname.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/management-and-monitoring/endpoint-management/schema-learning.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Schema learning

Cloudflare learns schema parameters via traffic inspection. For all endpoints saved to Endpoint Management, you can export the learned schema in OpenAPI `v3.0.0` format by hostname.

To protect your API with a learned schema, refer to [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/#add-validation-by-applying-a-learned-schema-to-an-entire-hostname).

## Export a schema

* [  New dashboard ](#tab-panel-3152)
* [ Old dashboard ](#tab-panel-3153)

1. In the Cloudflare dashboard, go to the **Web Assets** page.  
[ Go to **Web assets** ](https://dash.cloudflare.com/?to=/:account/:zone/security/web-assets)
2. Go to the **Endpoints** tab.
3. Select **Export schema** and choose a hostname to export.
4. Select whether to include learned parameters and rate limit recommendations
5. Select **Export schema** and choose a location to save the file.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/), and select your account and domain.
2. Select **Security** \> **API Shield** \> **Endpoint Management**.
3. Select **Export schema** and choose a hostname to export.
4. Select whether to include [learned parameters](https://developers.cloudflare.com/api-shield/management-and-monitoring/#learned-schemas-will-always-include) and [rate limit recommendations](https://developers.cloudflare.com/api-shield/security/volumetric-abuse-detection/)
5. Select **Export schema** and choose a location to save the file.

Note

The schema is saved as a JSON file in OpenAPI `v3.0.0` format.

Learned schemas will always include:

* The listed hostname in the servers section
* All endpoints by host, method, and path

For endpoints that receive sufficient traffic, learned schemas will also include:

* Detected path variables and formats
* Detected query parameters and formats
* Detected `POST`, `PUT`, and `PATCH` body variable names and formats for `application/json` content types

Learned schemas can optionally include:

* API Shield's rate limit threshold recommendations

## Limitations

Endpoints must be added for at least 24 hours before schema learning begins. Schema learning is a continuous process that inspects the last 72 hours of traffic to an endpoint.

Schema learning only learns from requests with `2xx` response codes.

Schema learning works best with high volumes of traffic. You may see less confident learned schemas for endpoints with less than 10,000 requests in the last 72 hours.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/management-and-monitoring/","name":"Management and Monitoring"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/management-and-monitoring/endpoint-management/","name":"Endpoint Management"}},{"@type":"ListItem","position":5,"item":{"@id":"/api-shield/management-and-monitoring/endpoint-management/schema-learning/","name":"Schema learning"}}]}
```

---

---
title: Session identifiers
description: While not strictly required, it is recommended that you configure your session identifiers when getting started with API Shield. When Cloudflare inspects your API traffic for individual sessions, we can offer more tools for visibility, management, and control.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/management-and-monitoring/session-identifiers.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Session identifiers

While not strictly required, it is recommended that you configure your session identifiers when getting started with API Shield. When Cloudflare inspects your API traffic for individual sessions, we can offer more tools for visibility, management, and control.

If you are unsure of the session identifiers that your API uses, consult with your development team.

Session identifiers should uniquely identify API clients. A common session identifier for API traffic is the `Authorization` header. When a [JSON Web Token (JWT)](https://developers.cloudflare.com/api-shield/security/jwt-validation/) is used by the API for client authentication, its value may change over time. You can use a claim value inside the JWT such as `sub` or `email` as a session ID to uniquely identify the session over time.

If your API uses the `Authorization` header on more than 1% of successful requests to your zone, Cloudflare will automatically set it as the API Shield session identifier.

Note

You must have specific entitlements to configure session identifiers or cookies as a form of identifiers, such as an Enterprise subscription, for features such as [API Discovery](https://developers.cloudflare.com/api-shield/security/api-discovery/), [Sequence Mitigation](https://developers.cloudflare.com/api-shield/security/sequence-mitigation/) or [rate limiting recommendations](https://developers.cloudflare.com/api-shield/security/volumetric-abuse-detection/), and to see results in [Sequence Analytics](https://developers.cloudflare.com/api-shield/security/sequence-analytics/) and [Authentication Posture](https://developers.cloudflare.com/api-shield/security/authentication-posture/).

## To set up session identifiers

* [  New dashboard ](#tab-panel-3154)
* [ Old dashboard ](#tab-panel-3155)

1. In the Cloudflare dashboard, go to the **Security Settings** page.  
[ Go to **Settings** ](https://dash.cloudflare.com/?to=/:account/:zone/security/settings)
2. Filter by **API abuse**.
3. On **Session identifiers**, select **Configure session identifiers**.
4. Select **Manage identifiers**.
5. Choose the type of session identifier (cookie, HTTP header, or JWT claim).  
Note  
The session identifier cookie must comply with RFC 6265\. Otherwise, it will be rejected.  
If you are using a JWT claim, choose the [Token Configuration](https://developers.cloudflare.com/api-shield/security/jwt-validation/api/#token-configurations) that will verify the JWT. Token Configurations are required to use JWT claims as session identifiers. Refer to [JWT Validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/) for more information.
6. Enter the name of the session identifier.
7. Select **Save**.

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com/login), and select your account and domain.
2. Go to **Security** \> **API Shield**.
3. Select **Settings**.
4. On **Endpoint settings**, select **Manage identifiers**.
5. Choose the type of session identifier (cookie, HTTP header, or JWT claim).  
Note  
The session identifier cookie must comply with RFC 6265\. Otherwise, it will be rejected.  
If you are using a JWT claim, choose the [Token Configuration](https://developers.cloudflare.com/api-shield/security/jwt-validation/api/#token-configurations) that will verify the JWT. Token Configurations are required to use JWT claims as session identifiers. Refer to [JWT Validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/) for more information.
6. Enter the name of the session identifier.
7. Select **Save**.

After setting up session identifiers and allowing some time for Cloudflare to learn your traffic patterns, you can view your per endpoint and per session rate limiting recommendations, as well as enforce per endpoint and per session rate limits by creating new rules. Session identifiers will allow you to view API Discovery results from session ID-based discovery and session traffic patterns in Sequence Analytics.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/management-and-monitoring/","name":"Management and Monitoring"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/management-and-monitoring/session-identifiers/","name":"Session identifiers"}}]}
```

---

---
title: Classic Schema validation (deprecated)
description: Use the API Shield interface to configure API Schema validation, which validates requests according to the API schema you provide.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/reference/classic-schema-validation.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Classic Schema validation (deprecated)

Deprecation notice

Classic Schema validation has been deprecated.

Upload all new schemas to [Schema validation 2.0](https://developers.cloudflare.com/api-shield/security/schema-validation/).

Use the **API Shield** interface to configure [API Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/), which validates requests according to the API schema you provide.

Before you can configure Schema validation for an API, you must obtain an API Schema file matching our [specifications](https://developers.cloudflare.com/api-shield/security/schema-validation/#specifications).

If you are in the Schema validation 2.0, you can make changes to your settings but you cannot add any new Classic Schema validation schemas.

Note

This feature is only available for customers on an Enterprise plan. Contact your Cloudflare Customer Success Manager to get access.

## Create an API Shield with Schema validation

To configure Schema validation in the Cloudflare dashboard:

1. Log in to the [Cloudflare dashboard ↗](https://dash.cloudflare.com) and select your account and domain.
2. Select **Security** \> **API Shield**.
3. Go to **Schema validation** and select **Add schema**.
4. Enter a descriptive name for your policy and optionally edit the expression to trigger Schema validation. For example, if your API is available at `http://api.example.com/v1`, include a check for the _Hostname_ field — equal to `api.example.com` — and a check for the _URI Path_ field using a regular expression — matching the regex `^/v1`.

Important

To validate the hostname, you must include the _Hostname_ field explicitly in the rule, even if the hostname value is in the schema file. Any hostname value present in the schema file will be ignored.

1. Select **Next**.
2. Upload your schema file.
3. Select **Save** to validate the content of the schema file and deploy the Schema validation rule. If you get a validation error, ensure that you are using one of the [supported file formats](https://developers.cloudflare.com/api-shield/security/schema-validation/#specifications) and that each endpoint and method pair has a unique operation ID.

After deploying your API Shield rule, Cloudflare displays a summary of all API endpoints organized by their protection level and actions that will occur for non-compliant and unprotected requests.

1. In the **Endpoint action** dropdown, select an action for every request that targets a protected endpoint and fails Schema validation.
2. In the **Fallthrough action** dropdown, select an action for every request that targets an unprotected endpoint.
3. Optionally, you can save the endpoints to Endpoint Management at the same time the Schema is saved by selecting **Save new endpoints to [endpoint management](https://developers.cloudflare.com/api-shield/management-and-monitoring/)**. Endpoints will be saved regardless of whether the Schema is saved as a draft or published live.
4. Select **Done**.

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/reference/","name":"Reference"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/reference/classic-schema-validation/","name":"Classic Schema validation (deprecated)"}}]}
```

---

---
title: Terraform
description: Get started with API Shield using Terraform from the examples below. For more information on how to use Terraform with Cloudflare, refer to the Terraform documentation.
image: https://developers.cloudflare.com/core-services-preview.png
---

[Skip to content](#%5Ftop) 

Was this helpful?

YesNo

[ Edit page ](https://github.com/cloudflare/cloudflare-docs/edit/production/src/content/docs/api-shield/reference/terraform.mdx) [ Report issue ](https://github.com/cloudflare/cloudflare-docs/issues/new/choose) 

Copy page

# Terraform

Get started with API Shield using Terraform from the examples below. For more information on how to use Terraform with Cloudflare, refer to the [Terraform documentation](https://developers.cloudflare.com/terraform/).

The following resources are available to configure through Terraform:

**Session identifiers**

* [api\_shield ↗](https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/api%5Fshield) for configuring session identifiers in API Shield.

**Endpoint Management**

* [api\_shield\_operation ↗](https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/api%5Fshield%5Foperation) for configuring endpoints in Endpoint Management.

**Schema validation**

* [cloudflare\_schema\_validation\_schemas ↗](https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/schema%5Fvalidation%5Fschemas) for configuring a schema in [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/).~~[api\_shield\_schema ↗](https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/api%5Fshield%5Fschema)~~ has been deprecated and will be removed in a future version of the terraform provider.
* [cloudflare\_schema\_validation\_settings ↗](https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/schema%5Fvalidation%5Fsettings) for configuring zone-level Schema validation settings.~~[api\_shield\_schema\_validation\_settings ↗](https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/api%5Fshield%5Fschema%5Fvalidation%5Fsettings)~~ has been deprecated and will be removed in a future version of the terraform provider.
* [cloudflare\_schema\_validation\_operation\_settings ↗](https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/schema%5Fvalidation%5Foperation%5Fsettings) for configuring operation-level Schema validation settings.~~[api\_shield\_operation\_schema\_validation\_settings ↗](https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/api%5Fshield%5Foperation%5Fschema%5Fvalidation%5Fsettings)~~ has been deprecated and will be removed in a future version of the terraform provider.

**JWT Validation**

* [cloudflare\_token\_validation\_config ↗](https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/token%5Fvalidation%5Fconfig) for setting up JWT validation with specific keying material and token locations.
* [cloudflare\_token\_validation\_rules ↗](https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/token%5Fvalidation%5Frules) for setting up rules to action on the validation result.

## Manage API Shield session identifiers

Refer to the example configuration below to set up [session identifiers](https://developers.cloudflare.com/api-shield/get-started/#to-set-up-session-identifiers) on your zone.

Example configuration

```

resource "cloudflare_api_shield" "session_identifiers" {

  zone_id = var.zone_id

  auth_id_characteristics = [{

    name = "authorization"

    type = "header"

  }]

}


```

## Manage API Shield Endpoint Management

Refer to the example configuration below to [manage endpoints](https://developers.cloudflare.com/api-shield/management-and-monitoring/) on your zone.

Example configuration

```

resource "cloudflare_api_shield_operation" "get_image" {

  zone_id  = var.zone_id

  method   = "GET"

  host     = "example.com"

  endpoint = "/api/images/{var1}"

}


resource "cloudflare_api_shield_operation" "post_image" {

  zone_id  = var.zone_id

  method   = "POST"

  host     = "example.com"

  endpoint = "/api/images/{var1}"

}


```

## Manage Schema validation

Note

It is required to configure Endpoint Management if you want to set up Schema validation using Terraform.

Refer to the example configuration below to manage [Schema validation](https://developers.cloudflare.com/api-shield/security/schema-validation/api/) on your zone.

Example configuration

```

# Schema that should be used for Schema validation

resource "cloudflare_schema_validation_schemas" "example_schema" {

  zone_id            = var.zone_id

  kind               = "openapi_v3"

  name               = "example-schema.yaml"

  # In this example, we assume that the `example-schema.yaml` includes `get_image` and `post_image` operations from above

  source             = file("./schemas/example-schema.yaml")

  validation_enabled = true

}


# Block all requests that violate schema by default

resource "cloudflare_schema_validation_settings" "zone_level_settings" {

  zone_id                              = var.zone_id

  validation_default_mitigation_action = "block"

}


# For endpoint post_image - only log requests that violate schema

resource "cloudflare_schema_validation_operation_settings" "post_image_log_only" {

  zone_id           = var.zone_id

  operation_id      = cloudflare_api_shield_operation.post_image.id

  mitigation_action = "log"

}


```

## Validate JWTs

Refer to the example configuration below to perform [JWT Validation](https://developers.cloudflare.com/api-shield/security/jwt-validation/) on your zone.

Example configuration

```

# Setting up JWT validation with specific keying material and location of the token

resource "cloudflare_token_validation_config" "example_es256_config" {

  zone_id       = var.zone_id

  token_type    = "JWT"

  title         = "ES256 Example"

  description   = "An example configuration that validates ES256 JWTs with `b0078548-c9bc-46e5-a678-06fb72443427` key ID in the authorization header"

  token_sources = ["http.request.headers[\"authorization\"][0]"]

  credentials   = {

    keys = [

      {

        alg = "ES256"

        kid = "b0078548-c9bc-46e5-a678-06fb72443427"

        kty = "EC"

        crv = "P-256"

        x   = "yl_BZSxUG5II7kJCMxDfWImiU6zkcJcBYaTgzV3Jgnk"

        y   = "0qAzLQe_YGEdotb54qWq00k74QdiTOiWnuw_YzuIqr0"

      }

    ]

  }

}


# Setting up JWT rules for all configured endpoints on `example.com` except for `get_image`

resource "cloudflare_token_validation_rules" "example_com" {

 zone_id      = var.zone_id

 title        = "Validate JWTs on example.com"

 description  = "This actions JWT validation results for requests to example.com except for the get_image endpoint"

 action       = "block"

 enabled      = true

 # Require that the JWT described through the example_es256_config is valid.

 # Reference the ID of the generated token config, this constructs: is_jwt_valid("<id>")

 # If the expression is >not true<, Cloudflare will perform the configured action on the request

 expression   = format("(is_jwt_valid(%q))", cloudflare_token_validation_config.example_es256_config.id)

 selector     = {

    # all current and future operations matching this include selector will perform the described action when the expression fails to match

    include = [

      {

        host          = ["example.com"]

      }

    ]

    exclude = [

      {

        # reference the ID of the get_image operation to exclude it

        operation_ids = ["${cloudflare_api_shield_operation.get_image.id}"]

      }

    ]

 }

}


# With JWT validation, we can also refine session identifiers to use claims from the JWT

resource "cloudflare_api_shield" "session_identifiers" {

  zone_id = var.zone_id

  auth_id_characteristics = [{

    # select the JWT's `sub` claim as an extremly stable session identifier

    # this is "<token_config_id:json_path>" format

    name = "${cloudflare_token_validation_config.example_es256_config.id}:$.sub"

    type = "jwt"

  }]

}


```

```json
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/api-shield/","name":"API Shield"}},{"@type":"ListItem","position":3,"item":{"@id":"/api-shield/reference/","name":"Reference"}},{"@type":"ListItem","position":4,"item":{"@id":"/api-shield/reference/terraform/","name":"Terraform"}}]}
```
