Token authentication allows you to restrict access to documents, files, and media to select users without requiring them to register. This helps protect paid/restricted content from leeching and unauthorized sharing.
There are two options to configure token authentication: via Cloudflare Workers or via custom rules.
Option 1: Configure using Cloudflare Workers
Refer to the following Cloudflare Workers resources for two different implementations of token authentication:
Use the Rules language is_timed_hmac_valid_v0() HMAC validation function to validate hash-based message authentication code (HMAC) tokens in a custom rule expression.
To validate token authentication, create a custom rule with a call to the is_timed_hmac_valid_v0() function in the rule expression. You can use an action such as Block.
Example rule
This example illustrates a rule that blocks any visitor that does not pass HMAC key validation on a specific hostname and URL path. Details required for token authentication include:
The secret key for generating and validating the HMAC (for example, mysecrettoken)
The path you wish to authenticate (for example, downloads.example.com/images/cat.jpg)
The name of the query string parameter containing the token (for example, verify)
The token lifetime in seconds (for example, 3 hours = 10,800 seconds)
The is_timed_hmac_valid_v0() function compares the value of a MAC generated using the mysecrettoken secret key to the value encoded in http.request.uri.
If the MAC values match and if the token has not expired yet, according to the following formula:
Then the token is valid and the is_timed_hmac_valid_v0() function returns true.
HMAC token generation
The following examples show how you could generate tokens at your origin server for the path validated using the custom rule described in the previous section:
For a full example in JavaScript (JS) or TypeScript (TS), refer to the Sign requests example in the Workers documentation.
Since the example JS/TS implementation is compatible with is_timed_hmac_valid_v0() function, requests authenticated using the provided source code can be verified with a WAF custom rule and the is_timed_hmac_valid_v0() function.
This will generate a URL parameter such as the following:
You can use the same secret key to protect several URI paths.
This is illustrated in the previous example, where http.request.uri is passed as the MessageMAC argument to the validation function.
Since http.request.uri includes the path to the asset and that value is extracted for each request, the validation function evaluates all request URIs to downloads.example.com using the same secret key.
Note that while you can use the same secret key to authenticate several paths, you must generate an HMAC token for each unique message you want to authenticate.