Learn how to set resource access permissions using Cloudflare Token Authentication.
Overview
Cloudflare Token Authentication allows you to restrict access to documents, files, and media to selected users without requiring registration. This can be used to protect paid/restricted content from leeching and non authorized sharing. Token Authentication can be easily implemented using the Cloudflare Web Application Firewall (WAF) and requires a Business level subscription or higher.
If you are looking into setting up token authentication for your application please submit a custom WAF rule request using the form available in the Firewall app under the Managed Rules tab by clicking the Request a rule link.
Please include the following information:
- The path you wish to authenticate (e.g. domain.com/download/*);
- The parameter name you wish the token to have (e.g. verify);
- Desired token expiry times if any (e.g. 5 and 20 minutes);
We will also need a shared secret of your choice, preferably of 32 bytes length, but do not send the shared secret with us via email; we will provide further instructions on how to do so.
Once the Cloudflare team has all the relevant information, custom WAF rules will be deployed in your account. Once available these will look like this:
You will be able to enable/disable each rule independently as well as test them on simulate.
Implement token creation
To implement the token creation requires the following code entered at your origin server:
PHP Version
<?php // Generate valid URL token
$secret = "thisisasharedsecret"; $time = time(); $token = $time . "-" . urlencode(base64_encode(hash_hmac("sha256", "/download/private.jpg$time", $secret, true)));
param = "verify=" . $token; ?>
Python Version
import hmac import base64 import time import urllib from hashlib import sha256 secret = "thisisasharedsecret" time = str(int(time.time())) digest = hmac.new(secret, "/download/cat.jpg" + time, sha256) param = urllib.urlencode({'verify': '%s-%s' % (time, base64.b64encode(digest.digest()))})
This will generate a URL parameter such as:
verify=1484063137-IaLGSmELTvlhfd0ItdN6PhhHTFhzx73EX8uy%2FcSDiIU%3D
Which you will then need to append to any URL under the domain.com/download/* path. For example:
/download/cat.jpg?verify=1484063787-9JQB8vP1z0yc5DEBnH6JGWM3mBmvIeMrnnxFi3WtJLE%3D
Please note that the token parameter needs to be the last parameter in the query string. You can test if URLs are being generated correctly on the server by enabling the WAF rules on simulate and monitoring the WAF logs and the Traffic section of the Cloudflare web portal.