Need help?

Our experts have had an average response time of 13.52 minutes in October 2021 to fix urgent issues.

We will keep your servers stable, secure, and fast at all times for one fixed price.

Cloudflare Token Authentication – How to Implement & Authenticate

by | Jun 30, 2021

With Cloudflare Token Authentication, we can restrict access to documents, files, and media to selected users without them registering.

This will eventually protect paid/restricted content from leeching and unauthorized sharing.

As part of our Server Management Services, we assist our customers with several Cloudflare queries.

Today, let us see how to enable token authentication in Cloudflare.

 

Cloudflare Token Authentication

Recently, one of our customers came across a “Sorry, you have been blocked” message while accessing sites using Cloudflare.

Generally, this happens when we try to access a restricted resource without a valid token.

Moving ahead, let us see how our Support Techs authenticate a token via Firewall Rules.

  • Configure using Firewall Rules

To do so, we require a Business or Enterprise account.

  1. Initially, we log in to the Cloudflare dashboard.
  2. Click the account for the domain we want to enable Token Authentication.
  3. Then we click on the Firewall app.
  4. In the Firewall Rules tab, we click Create a Firewall Rule.
  5. To switch to the Expression Preview editor, we click the Edit expression link.

Now, let us see a rule that blocks any visitor that does not pass the HMAC key validation on a specific hostname and URL path.

For instance, consider the below URL:

test.domain.com/download/cat.jpg?verify=1484063787-9JQB8vP1z0yc5DEBnH6JGWM3mBmvIeMrnnxFi3WtJLE%3D

The example Firewall Rule for this will look like this:

(http.host eq “test.domain.com” and not is_timed_hmac_valid_v0(“mysecrettoken”, http.request.uri,10800, http.request.timestamp.sec,8))

The components of this example Firewall Rule include:

  • Token key = mysecrettoken
  • Token expiration time = 10800 seconds
  • Http.request.uri = /download/cat.jpg
  • Http.request.timestamp.sec = 1484063787
  • Separator: len(?verify=) = 8

Moving ahead, let us see how to generate tokens for the paths using this Firewall Rule:

Python 3.8

import hmac
import base64
import urllib.parse
import time
from hashlib import sha256
message = "/download/cat.jpg"
secret = "mysecrettoken"
separator = "?verify="
timestamp = str(int(time.time()))
digest = hmac.new((secret).encode('utf8'), "{}{}".format(message,timestamp).encode('utf8'), sha256)
token = urllib.parse.quote_plus(base64.b64encode(digest.digest()))
print("{}{}{}-{}".format(message, separator, timestamp, token))

Python 2.7

import hmac
import base64
import time
import urllib
from hashlib import sha256
message = "/download/cat.jpg"
secret = "mysecrettoken"
separator = "verify"
timestamp = str(int(time.time()))
digest = hmac.new(secret, message + timestamp, sha256)
param  = urllib.urlencode({separator: '%s-%s' % (timestamp, base64.b64encode(digest.digest()))})
print("{}{}".format(message, param))

PHP

$message = "/download/cat.jpg";
$secret = "mysecrettoken";
$separator = "?verify=";
$time   = time();
$token  = $time . "-" . urlencode(base64_encode(hash_hmac("sha256", $message . $time, $secret, true)));
echo($message . $separator . $token);

 

Implement token creation

To implement the token creation we need to enter the following code at the 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:

verify=1484063137-IaLGSmELTvlhfd0ItdN6PhhHTFhzx73EX8uy%2FcSDiIU%3D

We will then need to append it to any URL under the domain.com/download/* path. For example,

/download/cat.jpg?verify=1484063787-9JQB8vP1z0yc5DEBnH6JGWM3mBmvIeMrnnxFi3WtJLE%3D

In order to check if URLs generate correctly on the server, we can enable the WAF rules. It will simulate and monitor the WAF logs and the Firewallapp in the Cloudflare dashboard.

[Need help with the procedure? We’d be happy to assist]

 

Conclusion

In short, we saw how our Support Techs authenticate token in Cloudflare.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = "owonCMyG5nEQ0aD71QM";

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Privacy Preference Center

Necessary

Necessary cookies help make a website usable by enabling basic functions like page navigation and access to secure areas of the website. The website cannot function properly without these cookies.

PHPSESSID - Preserves user session state across page requests.

gdpr[consent_types] - Used to store user consents.

gdpr[allowed_cookies] - Used to store user allowed cookies.

PHPSESSID, gdpr[consent_types], gdpr[allowed_cookies]
PHPSESSID
WHMCSpKDlPzh2chML

Statistics

Statistic cookies help website owners to understand how visitors interact with websites by collecting and reporting information anonymously.

_ga - Preserves user session state across page requests.

_gat - Used by Google Analytics to throttle request rate

_gid - Registers a unique ID that is used to generate statistical data on how you use the website.

smartlookCookie - Used to collect user device and location information of the site visitors to improve the websites User Experience.

_ga, _gat, _gid
_ga, _gat, _gid
smartlookCookie

Marketing

Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user and thereby more valuable for publishers and third party advertisers.

IDE - Used by Google DoubleClick to register and report the website user's actions after viewing or clicking one of the advertiser's ads with the purpose of measuring the efficacy of an ad and to present targeted ads to the user.

test_cookie - Used to check if the user's browser supports cookies.

1P_JAR - Google cookie. These cookies are used to collect website statistics and track conversion rates.

NID - Registers a unique ID that identifies a returning user's device. The ID is used for serving ads that are most relevant to the user.

DV - Google ad personalisation

IDE, test_cookie, 1P_JAR, NID, DV, NID
IDE, test_cookie
1P_JAR, NID, DV
NID
hblid

Security

These are essential site cookies, used by the google reCAPTCHA. These cookies use an unique identifier to verify if a visitor is human or a bot.

SID, APISID, HSID, NID, PREF
SID, APISID, HSID, NID, PREF