Support

Find answers, guides, and tutorials to supercharge your content delivery.

Secure Token

Updated on October 4, 2018

Token authentication ensures that a URL is only accessible during a defined Unix time. You can define the time frame with an exact expiration time. Once a token has expired, it is not possible anymore to access the content. Several tokens with different expiration times can be created for the same file. A 403 Forbidden will be return if the token is not valid and a 410 Gone if the Secure Token has already expired.

Format

http://yourzone-id.kxcdn.com{path}?token={token}&expire={timestamp}

Setup token authentication

  1. Log in to the KeyCDN dashboard.
  2. In the left navigation sidebar click Zones.
  3. In the Zones table click the Zone menu that you want add token authentication to and click Edit.
  4. Update the Secure Token setting to enabled.
  5. Define a Secure Token Key. This key will be needed to generate the token.
  6. Use one of the following code examples to generate the token (e.g. from your website).
Note: If using a Pull Zone for token authentication we recommend ensuring the Origin URL is not public and can't be easily guessed.

PHP

<?php
    $secret = 'securetokenkey';
    $path = '/path/to/file1.jpg';

    // Expiration in seconds (e.g. 90 seconds)
    $expire = time() + 90;

    // Generate token
    $md5 = md5($path.$secret.$expire, true);

    $md5 = base64_encode($md5);
    $md5 = strtr($md5, '+/', '-_');
    $md5 = str_replace('=', '', $md5);

    // Use this URL
    $url = "http://yourzone-id.kxcdn.com{$path}?token={$md5}&expire={$expire}";

    echo $url;
?>

Python

import base64
from hashlib import md5
from time import time

secret = 'your_secret'
path = "/path/to/file1.jpg"

# expiration in seconds (e.g. 180 seconds)
expire = int(time()) + 180

# generate token
token = base64.encodestring(
    md5(
        "%s%s%s" % (path, secret, expire)
    ).digest()
).replace("\n", "").replace("+", "-").replace("/", "_").replace("=", "")
secured_url = "http://demo-1.kxcdn.com%s?token=%s&expire=%s" % (path, token, expire)

# return secured URL
print secured_url

Ruby

require 'digest/md5'
require 'base64'

secret = 'your_secret'
path = '/path/to/your/file.jpg'

# expiry time in seconds (e.g. 3600 seconds)
expire = Time.now.to_i + 3600
token = Base64.encode64(
    Digest::MD5.digest(
        "#{path}#{secret}#{expire}"
    )
).gsub("\n", "").gsub("+", "-").gsub("/", "_").gsub("=", "")

# final secured URL
url = "http://demo-1.kxcdn.com#{path}?token=#{token}&expire=#{expire}"

puts url

Node.js

var crypto = require('crypto'),
    secret = 'your_secret',
    path = '/path/to/your/file.jpg';

// define expiry (e.g. 120 seconds)
var expire = Math.round(Date.now()/1000) + 120;

// generate md5 token
var md5String = crypto
    .createHash("md5")
    .update(path + secret + expire)
    .digest("binary");

// encode and format md5 token
var token = new Buffer(md5String, 'binary').toString('base64');
token = token.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');

// return secure token
console.log('http://demo-1.kxcdn.com' + path + '?token=' + token + '&expire=' + expire);

Java

import java.util.Date;
import org.apache.commons.codec.binary.Base64;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;

public class getSecureURL {

    // generate token
    private static String getBinaryToken(String path, String secret, Long expire) throws UnsupportedEncodingException, NoSuchAlgorithmException{

        String urlData = path + secret + expire.toString();
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(urlData.getBytes());
        String token = Base64.encodeBase64URLSafeString(messageDigest);

        return token;

    }

    // main method
    public static void main(String[] args) throws Exception{

        String secret = "your_secret";
        String path = "/path/to/your/file.jpg";

        Date date = new Date();
        // expiry time (e.g. 300 seconds)
        Long expire = (date.getTime()/1000) + 300;
        String token = "" ;

        try {
            md5 = getBinaryToken(path, secret, expire);

            // final secured URL with token and expire variables
            String url = "http://demo-1.kxcdn.com" + path + "?token=" + md5 + "&expire=" + expire.toString() ;
            System.out.println("genrated url : " + url);
        } catch (Exception e){
            e.printStackTrace();
        }

    }

}

Example:

http://yourzone-id.kxcdn.com/path/to/file1.jpg?token=85b9a81b78b24b4d18303c91b79e0124&expire=1384719072

Generate a Secure Token with OpenSSL

echo -n '{path}{secret}{timestamp}' | openssl md5 -binary | openssl base64 | tr +/ -_ | tr -d =

Example:

echo -n '/path/to/file1.jpgmysecret1384719072' | openssl md5 -binary | openssl base64 | tr +/ -_ | tr -d =

Supercharge your content delivery 🚀

Try KeyCDN with a free 14 day trial, no credit card required.

Get started
KeyCDN uses cookies to make its website easier to use. Learn more about cookies.