How do I set up Signed URLs?

Secure Token allows you to generate secured links with expiration time, making your files available for only selected time period via the generated URL. It is best to use it in combination with some unpredictable / secure origin, which your visitors cannot guess, or with our CDN Storage set as origin.

How to proceed:

1. Create a CDN Resource with an unpredictable origin such as:

      fewnuwefi36a6d.SomeUnpredictableDomain.com
    
or with CDN Storage set as origin.

Important: You need to own this domain. If you do not want to buy a new domain, you can use a subdomain which can't be guessed.

2. Once you've created your new CDN Resource, you need to enable the Secure Token option in the CDN Resource Access Protection section. There are two options to choose from. You can select, If the Secure Token will be used as a parameter in the URL, or if it will be inclueded inside the path to the file.

  • Parameter - New URL have to be generated for each separate file. The URL for the files then looks the same, just at the end of it, query string is added for the secure token. Based on this query string, the validity of the URL is decided. Example:

            http://www.example.com/images/photo.png?secure=kaGd_cu6Iy4LDgfX3jy5Rw==,1333497600
          
  • Path - The secure token string, based on which the validity of the URL is decided, is added to the path for the file inside the URL, instead of the end. It is added right after the first slash, after the domain (the CDN URL or your CNAME). The secure URL is then valid for all the files, present in the last folder and any subfolder. You must use at least one folder in the path to your files with this option. Example:

            http://www.example.com/kaGd_cu6Iy4LDgfX3jy5Rw==,1333497600/images/photo.png
          

    You could then use the same secure URL for different files inside the "images" folder and any subfolders:

            http://www.example.com/kaGd_cu6Iy4LDgfX3jy5Rw==,1333497600/images/photo2.png
            http://www.example.com/kaGd_cu6Iy4LDgfX3jy5Rw==,1333497600/images/sub1/sub2/sub3/photo3.png
          

3. After enabling Secure Token the secret password token will be displayed in the CDN Resource Access Protection section (CDN tab in the client zone). You must use this token in order to generate the signed URLs.

4. Once you have followed all the steps you can generate signed URLs. Use one of the following PHP functions to integrate it.

Generate the signed URLs for the Parameter secure token option

To generate using the Parameter secure token option, use the following code example:

    <?php
    /**
    * Create hash link CDN resource
    *
    * @param string $cdnResourceUrl
    * @param string $filePath
    * @param string $secureToken
    * @param ?int $expiryTimestamp
    * @return string
    */
    function getSignedUrlParameter(string $cdnResourceUrl, string $filePath, string $secureToken, ?int $expiryTimestamp = NULL) : string
    {
    	// replace invalid URL query string characters +, =, / with valid characters -, _, ~
    	$invalidChars = ['+','/'];
    	$validChars = ['-','_'];

    	if ($filePath[0] != '/') {
    		$filePath = '/' . $filePath;
    	}

    	if ($pos = strpos($filePath, '?')){
    		$filePath = substr($filePath, 0, $pos);
    	}

    	$hashStr = $filePath.$secureToken;

    	if ($expiryTimestamp){
    		$hashStr = $expiryTimestamp . $hashStr;
    		$expiryTimestamp = ',' . $expiryTimestamp;
    	}

    	return 'http://' . $cdnResourceUrl . $filePath . '?secure='.
    		str_replace($invalidChars, $validChars, base64_encode(md5($hashStr, TRUE))).
    		$expiryTimestamp;
    }
  

Usage example

Generate hash link for resource www.example.com/images/photo.png for next 3 days, assume today is Sun, 01 Apr 2012

    $signedUrlParameter = getSignedUrlParameter('www.example.com', '/images/photo.png', 'ykX1QNTRvp3tfSn8', 1389183132);

    // http://www.example.com/images/photo.png?secure=w1YyQPIQNUpX1cXKNrxgdA==,1389183132
    print $signedUrlParameter;
  

Generate the signed URLs for the Path secure token option

To generate using the Path secure token option, use the following code example:

    <?php

    /**
    * Create hash link Path CDN Resource
    *
    * @param string $cdnResourceUrl
    * @param string $filePath
    * @param string $secureToken
    * @param ?int $expiryTimestamp
    * @return string
    */
    function getSignedUrlPath(string $cdnResourceUrl, string $filePath, string $secureToken, ?int $expiryTimestamp = NULL) : string
    {
        // because of hls/dash, anything included after the last slash (e.g. playlist/{chunk}) shouldn't be part of the path string,
        // for which we generate the secure token. Because of that, everything included after the last slash is stripped.
        $strippedPath = substr($filePath, 0, strrpos($filePath, '/'));

        // replace invalid URL query string characters +, =, / with valid characters -, _, ~
      	$invalidChars = ['+','/'];
      	$validChars = ['-','_'];

        if ($strippedPath[0] != '/') {
            $strippedPath = '/' . $strippedPath;
        }

        if ($pos = strpos($strippedPath, '?')) {
            $filePath = substr($strippedPath, 0, $pos);
        }

        $hashStr = $strippedPath . $secureToken;

        if ($expiryTimestamp) {
            $hashStr = $expiryTimestamp . $hashStr;
            $expiryTimestamp = ',' . $expiryTimestamp;
        }

        // the URL is however, intensionaly returned with the previously stripped parts (eg. playlist/{chunk}..)
        return 'http://' . $cdnResourceUrl . '/' .
            str_replace($invalidChars, $validChars, base64_encode(md5($hashStr, TRUE))) .
            $expiryTimestamp . $filePath;
    }
  

Usage example

    $signedUrlPath = getSignedUrlPath('12121.rsc.cdn77.org', '/file/playlist/d.m3u8', 'ykX1QNTRvp3tfSn8', 1389183132);

    // http://12121.rsc.cdn77.org/z--FA_CsNsR2TOV2eg9q4w==,1389183132/file/playlist/d.m3u8
    print $signedUrlPath;
  

Parameters description

Parameter Example Description
$cdnResourceUrl string* cdn.yourdomain.com The CDN resource URL, eg. cdn.yourdomain.com
$filePath string* /images/photo.png File path of the CDN resource.
$secureToken string* ykX1QNTRvp3tfSn8 The secret key that is obtained from CDN resource property Access Protection.
$expiryTimestamp int* 1389183132 UNIX timestamp format, specify how long the hash link is accessible to the public.

Here is an example of it being used.

Let's say we host some video content on our website http://myvideos123.com, which we want to provide only to selected users (probably VIP clients or paying members).

We move all the content we want to secure to an unguessable domain, created and bought just for this purpose.

Example of the domain:

Strongly secured: sdfs55sdf8gfdhd.df88af6sdfgdfg54sdf.com

Weakly secured: content.myvideos123.com

Then we create a new CDN Resource and enter the domain above in the origin server URL field.

Now we can generate the link for the users via the function above.

The final link for the visitor (customer) will look like this:

    http://www.example.com/images/photo.png?secure=kaGd_cu6Iy4LDgfX3jy5Rw==,1333497600
  

or:

    http://www.example.com/kaGd_cu6Iy4LDgfX3jy5Rw==,1333497600/images/photo.png
  

It will be valid till 2:17:32 on the 6th of April 2012. (Unix timestamp: 1333497600). It's smart to set the expiration time as current time plus 5 minutes { time() + 300}. This way the link will be available only for the time needed to start the download. Afterwards a new link must be generated in order to download this content again.

Thanks to one of our clients, a library based on the PHP example above has been written (only for generating URLs using te Parameter query string option).