Videos

Token Authentication

You can generate unique secure tokens for every video to enable authenticated video plays. A tokenized URL provides temporary access to your HLS video.

Example tokenized URL:

example
https://api.dyntube.com/v1/live/videos/tokens/TKMfds6D2ImFVA.m3u8?token=oXPAQ0TixktGi8WEKKJSDHJ&expires=1656597538

Follow these steps to generate tokenized video URLs.

Step 1. Get Security Key

Get the security key for token authentication from the dashboard. Below is the path in the dashboard:

example
Projects => Global Settings => API keys.

Step 2. Get Video Key

Use the Get Videos endpoint and store the videos in your database for future reference. The token flow uses the key field from each video object; this guide refers to that value as videoKey.

Step 3. Generate Token

The token is a Base64-encoded SHA256 hash built from the inputs below. Three inputs are required, and the remaining parameters are optional.

Unix timestamp. The token expires after this time.

Restrict playback to viewers in the provided countries. If this parameter is empty, playback is allowed from all countries.

If IP addresses are not provided, all IPs are allowed.

  1. securityKey (required)
  2. expires (required)\
  3. videoKey (required)
  4. countries (optional, comma-separated TWO letter country codes). \
  5. ips(optional, comma separated IP addresses).\
  6. views (optional). The total number of allowed video views.

Here is a code example in Node.js

javascript
const express = require('express')
const app = express()
const port = 3000
global.crypto = require('crypto')

app.get('/', (req, res) => {
  
  const securityKey="[API_SECURITY_KEY]";
  const now = new Date();
  now.setDate(now.getDate() + 1);
  const expiryTime=Math.floor(now);
  const videoKey="[VIDEO_KEY]";
  const countries="",ips="";
  const views=0;
  
  var tokenInput = securityKey + expiryTime + countries + ips + videoKey;
  tokenInput = views > 0 ? tokenInput + views.toString() : tokenInput;
  
  var token = Buffer.from(crypto.createHash("sha256").update(tokenInput).digest()).toString("base64");
  token = token.replace(/\n/g, '').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
  
  res.send(`https://api.dyntube.com/v1/live/videos/tokens/${videoKey}.m3u8?token=${token}&expires=${expiryTime}`
  + (countries ? `&countries=${countries}` : '')+ (ips ? `&ips=${ips}` : '')+ (views> 0 ? `&views=${views}` : ''));
  
})

app.listen(port, () => {
  console.log(`app listening on port localhost:${port}`)
})

Here is a code example in C\#

csharp
using System;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string securityKey = "your_security_key_here";
        long unixTimeMilliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();
        string videoKey = "your_video_key_here";
        string countries = "US,CA";
        string ips = "192.168.1.1,192.168.1.2";
        long views = 5;

        string token = GenerateToken(securityKey, unixTimeMilliseconds, videoKey, countries, ips, views);
        Console.WriteLine(token);
    }

    private static string GenerateToken(string securityKey, long unixTimeMilliseconds, string videoKey, string countries = "", string ips = "", long views = 0)
    {
        var tokenInput = securityKey + unixTimeMilliseconds + countries + ips + videoKey;
        tokenInput = views > 0 ? tokenInput + views : tokenInput;

        var bytes = Encoding.UTF8.GetBytes(tokenInput);
        var hash = new SHA256Managed().ComputeHash(bytes);
        var token = Convert.ToBase64String(hash);
        return token.Replace("\n", "").Replace("+", "-").Replace("/", "_").Replace("=", "");
    }
}

Python sample

python
import hashlib
import base64
import time

def generate_token(security_key: str, unix_time_milliseconds: int, video_key: str, countries: str = '', ips: str = '', views: int = 0) -> str:
    token_input = security_key + str(unix_time_milliseconds) + countries + ips + video_key
    token_input = token_input + str(views) if views > 0 else token_input

    hash_value = hashlib.sha256(token_input.encode()).digest()
    token = base64.b64encode(hash_value).decode().replace('\n', '').replace('+', '-').replace('/', '_').replace('=', '')
    return token

PHP Sample

php
function generateToken($securityKey, $unixTimeMilliseconds, $videoKey, $countries = "", $ips = "", $views = 0) {
    $tokenInput = $securityKey . $unixTimeMilliseconds . $countries . $ips . $videoKey;
    $tokenInput = $views > 0 ? $tokenInput . $views : $tokenInput;

    $hash = hash("sha256", $tokenInput, true);
    $token = base64_encode($hash);
    $token = str_replace("\n", "", $token);
    $token = str_replace("+", "-", $token);
    $token = str_replace("/", "_", $token);
    $token = str_replace("=", "", $token);

    return $token;
}

You can call this function by passing in the required parameters, like this:

perl
$securityKey = "your_security_key_here";
$unixTimeMilliseconds = time() * 1000; // current time in milliseconds
$videoKey = "your_video_key_here";
$countries = ""; // optional
$ips = ""; // optional
$views = 0; // optional

$token = generateToken($securityKey, $unixTimeMilliseconds, $videoKey, $countries, $ips, $views);

// Use the token to build the HLS URL
$hlsUrl = "https://api.dyntube.com/v1/live/videos/tokens/{$videoKey}.m3u8?token={$token}&expires={$unixTimeMilliseconds}&countries={$countries}&ips={$ips}&views={$views}";

Steps To Generate a Token

  1. Concatenate all parameters in the specified order: securityKey + expires + countries + ips + videoKey. Use empty strings for countries and ips when you do not need those restrictions.
  2. If views is greater than zero, append it to the tokenInput.
  3. Convert the concatenated string tokenInput into a byte array.
  4. Get the SHA256 hash of the byte array.
  5. Convert the hashed value to a Base64 string.
  6. Replace the following characters in the generated Base64 string:
  7. \n → (remove)
  8. + → -
  9. / → _
  10. = → (remove)

Step 4. Build a Tokenized Video URL

Once you have generated the token, you can use it to build a tokenized URL for your video.

URL Format:

example
https://api.dyntube.com/v1/live/videos/tokens/{videoKey}.m3u8?token={TOKEN}&expires={UNIX_TIMESTAMP}&countries={COUNTRIES}&ips={IPS}&viewId={VIEW_ID}&views={NUMBER}

Example with all parameters:

example
https://api.dyntube.com/v1/live/videos/tokens/TKMfds6D2ImFVA.m3u8?token=oXPAQ0TixktGi8WEKKJSDHJ&expires=16597538&countries=AU,US&ips=1.1.1.1&viewId=abc&views=10

Example without optional parameters:

example
https://api.dyntube.com/v1/live/videos/tokens/TKMfds6D2ImFVA.m3u8?token=oXPAQ0TixktGi8WEKKJSDHJ&expires=1656597538
  • Get videos to retrieve the key value used as videoKey.
  • Get video for mobile app/custom player for direct playback field guidance.
  • Create expirable links when you want DynTube-hosted browser playback links instead of signed HLS URLs.

Something missing or wrong here? Tell us and we will correct it. New to DynTube? Start with uploading and embedding.