Configure JWT validation via the API·续

Selector examplejson

{
    "include": [
        {
            "host": ["v1.example.com", "v2.example.com"]
        }
    ],
    "exclude": [
        {
            "operation_ids": [
                "f9c5615e-fe15-48ce-bec6-cfc1946f1bec",
                "56828eae-035a-4396-ba07-51c66d680a04"
            ]
        }
    ]
}

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.

Use the page and per_page query parameters to paginate operations. They default to page 1 and 20 operations per page. Each response includes one page in result.operations and pagination metadata in result_info.

Example using cURLbash

curl --request POST \
'https://api.cloudflare.com/client/v4/zones/{zone_id}/token_validation/rules/preview?page=1&per_page=20' \
--header 'Content-Type: application/json' \
--data '{
    "include": [
        {
            "host": [
                "v1.example.com",
                "v2.example.com"
            ]
        }
    ],
    "exclude": [
        {
            "operation_ids": [
                "f9c5615e-fe15-48ce-bec6-cfc1946f1bec",
                "56828eae-035a-4396-ba07-51c66d680a04"
            ]
        }
    ]
}'

The response includes one page of 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.

Resultjson

{
    "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",
            "v2.example.com",
            "v3.example.com"
        ]
    },
    "success": true,
    "errors": [],
    "messages": [],
    "result_info": {
        "page": 1,
        "per_page": 20,
        "count": 7,
        "total_count": 7
    }
}

Operations with an 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 cURLbash

curl --request POST \
'https://api.cloudflare.com/client/v4/zones/{zone_id}/token_validation/rules/preview' \
--header 'Content-Type: application/json' \
--data '{ }'

The response shows one page of 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 examplejson

[
    {
        "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 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 cURLbash

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.

Resultjson

{
    "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 regularly. You can add a new key, start issuing JWTs with that key, and then remove the old key.

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.

Credential updates use the same algorithm defaulting behavior as configuration creation. The response includes normalized credentials in result and one message for each defaulted algorithm.

Use PUT to replace the complete key set. Every symmetric key in a PUT request must include k. Keys omitted from the request are removed.

Example using cURLbash

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 header.

Preserve or rotate a symmetric credential

Use PATCH to update the complete key set without resubmitting stored symmetric credentials. Cloudflare matches an existing key using its alg and kid values.

  • Omit k for a matching symmetric key to preserve its credential.
  • Include a new k value to rotate the credential.
  • Include k when adding a symmetric key that does not already exist.
  • Omit a key from keys to remove it from the configuration.
  • Do not set k to null.

This example preserves the credential for production-hmac-key while adding an EC key:

Preserve a symmetric credentialbash

curl --request PATCH \
'https://api.cloudflare.com/client/v4/zones/{zone_id}/token_validation/config/{config_id}/credentials' \
--header 'Content-Type: application/json' \
--data '{
    "keys": [
        {
            "kty": "oct",
            "alg": "HS256",
            "kid": "production-hmac-key"
        },
        {
            "kty": "EC",
            "alg": "ES256",
            "crv": "P-256",
            "kid": "production-ec-key",
            "x": "<BASE64URL_ENCODED_X_COORDINATE>",
            "y": "<BASE64URL_ENCODED_Y_COORDINATE>"
        }
    ]
}'

This example rotates the credential for the existing HMAC key:

Rotate a symmetric credentialbash

curl --request PATCH \
'https://api.cloudflare.com/client/v4/zones/{zone_id}/token_validation/config/{config_id}/credentials' \
--header 'Content-Type: application/json' \
--data '{
    "keys": [
        {
            "kty": "oct",
            "alg": "HS256",
            "kid": "production-hmac-key",
            "k": "<NEW_BASE64URL_ENCODED_SECRET>"
        }
    ]
}'

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 cURLbash

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 cURLbash

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 cURLbash

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. Cloudflare makes verified claims available as http.request.jwt.claims fields. WAF custom rules can act on these claims. Token validation rules can act on token presence and validity.
  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.

Was this helpful?

YesNo

On this page

Configure JWT validation via the API·续 - 图1Docs

{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/api-shield/security/jwt-validation/api/#page","headline":"Configure JWT validation via the API","description":"Configure JWT validation and act on its results using the Cloudflare API.","url":"https://developers.cloudflare.com/api-shield/security/jwt-validation/api/","inLanguage":"en","image":"https://developers.cloudflare.com/api-shield/security/jwt-validation/api/og.png?v=2a0c992fe482f981","dateModified":"2026-10-06","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"},"keywords":["JSON web token (JWT)"]}


description: Use a Worker to keep your identity provider public keys updated for JWT validation. title: Configure the Worker image: https://developers.cloudflare.com/api-shield/security/jwt-validation/jwt-worker/og.png?v=6411790a1866f55f


Skip to content

Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/api-shield/llms.txt
Use this file to discover all available pages before exploring further.