Skip to content
Search Documentation
Search across all documentation pages
Protected Playback

Protected Playback

Overview

Protected playback lets your server decide who watches a video in the Transcodely hosted player. For each signed-in viewer, your server makes a short-lived playback token for one video and adds it to the player URL:

https://play.transcodely.com/v/vid_a1b2c3d4e5f6g7?token=ptk_eyJhbGciOi...

With a valid token the player plays the video, including a private one, which never plays without a token. The token can also carry:

  • a viewer id, your own identifier for the buyer, which turns on cross-device resume and server-side progress (see Course Progress),
  • a line of overlay text drawn over the video, for example the buyer’s email address,
  • a resolution cap, the highest rendition the player may pick.

On top of tokens, an app can list allowed embed domains: when the list is set, browsers refuse to show the app’s player framed on any other site.

Public and unlisted videos with no token behave exactly as before. Tokens and domains are both optional, and both default to off.


How it fits together

  1. In the dashboard, create a playback signing key for your app (or skip this and let the API sign for you, below).
  2. When a signed-in viewer opens a lesson, your server makes a token for that viewer and that video: locally with the key (no network call), or with one API call.
  3. Your page embeds the player with the token in its URL.
  4. The player page checks the token. If it is valid it renders the player with stream URLs that expire no later than the token.
Video visibilityNo tokenValid tokenInvalid, expired, other video, other app, or revoked key
publicPlaysPlays, with the token’s overlay, viewer id and cap404
unlistedPlaysPlays, with the token’s overlay, viewer id and cap404
private404Plays404

A bad token on a public video is a 404 rather than a silent fallback, so a broken integration shows up while you build it.


Signing keys

A playback signing key has an id and a secret:

ThingFormat
Key idpsk_ followed by 14 characters, for example psk_a1b2c3d4e5f6g7. Goes in every token’s header.
Secretpss_ followed by 43 characters. Shown once, when the key is created or rotated.

Create keys in the dashboard: open the app, then Playback security. Creating, rotating and deleting keys needs the owner or admin role; every member can see the list. The same operations are available to the app’s API keys through PlaybackSigningKeyService (Create, List, Rotate, Delete): see the Playback Signing Keys reference.

An app can have at most 5 keys that have not expired.

Store the key id and the secret on your server, for example in environment variables. Never put the secret in a browser, a mobile app or a public repository: anyone holding it can make tokens for every video of the app.

Rotation is how you revoke

Tokens are not stored anywhere, so a single token cannot be revoked. Rotating its signing key can:

  • Rotate creates a new key, with a new id and a new secret, and makes the old key expire after an overlap you choose: immediately, 1 hour, 24 hours (the default) or 7 days. During the overlap, tokens signed with either key open the player, so your servers can switch over without interrupting viewers. Rotating works at the 5-key limit too: the key being rotated does not count against it.
  • Rotate immediately (expire_previous_in: 0) when a secret leaks: from that moment, no token the old key signed opens the player.
  • Delete a key to expire it now. It stays listed with status expired.
  • A key that was already rotated (status expiring) cannot be rotated again (failed_precondition); rotate its replacement.

Revocation is checked when the player page loads. Once a key has expired, new page loads with its tokens are refused straight away, but a player that is already open keeps playing until its stream URLs expire: at the token’s exp or 6 hours after that page loaded, whichever comes first. Short token lifetimes keep that window small.

curl -X POST https://api.transcodely.com/transcodely.v1.PlaybackSigningKeyService/Rotate 
  -H "Authorization: Bearer $TRANSCODELY_API_KEY" 
  -H "Content-Type: application/json" 
  -d '{"id": "psk_a1b2c3d4e5f6g7", "expire_previous_in": 86400}'

The response carries the new key, its secret (shown only here) and the previous key, now expiring. Update both the key id and the secret on your servers.


Minting tokens

The token format

A playback token is a compact JWT signed with HMAC-SHA256 (HS256), with the literal prefix ptk_:

ptk_<base64url(header)>.<base64url(claims)>.<base64url(signature)>

The header is {"alg":"HS256","kid":"<key id>","typ":"JWT"}. alg must be HS256 and kid is required.

ClaimTypeRequiredMeaning
vidstringyesThe video id (vid_…). The token plays this video only.
expintegeryesExpiry, Unix seconds. At most 24 hours ahead; a later expiry is refused, not shortened.
substringnoViewer id: your own opaque identifier for the viewer, 1 to 128 characters with no control characters (line breaks, tabs, NUL), and at most 512 bytes once JSON-encoded (anything else makes the token invalid). Not an email address or a name.
ovlstringnoOverlay text, 1 to 80 characters.
cmpnumbernoCompletion threshold the server uses for this viewer’s progress record and the video.viewer.completed webhook: the share of the video the viewer must actually play, 0.1 to 1.0. Default 0.9. See Course Progress.
mrstringnoHighest rendition: 480p, 720p, 1080p, 1440p or 2160p.

Unknown claims are ignored.

The claims are signed, not encrypted. Anyone who sees the player URL can decode the token and read sub and ovl, and the full URL, token included, can appear in browser history and in infrastructure request logs along the way. Keep sub an opaque id that means nothing outside your own database, and treat ovl as text that is visible to whoever holds the URL.

To sign:

  1. Encode the header and the claims as JSON, UTF-8, then base64url without padding (RFC 4648 §5).
  2. Join them with a dot: that is the signing input.
  3. HMAC-SHA256 the signing input with the whole secret string as the key, pss_ prefix included, as UTF-8 bytes. Do not base64-decode the secret.
  4. The token is ptk_ + signing input + . + base64url of the signature.

Any valid JSON encoding verifies: key order and whitespace do not matter.

On your server

With an SDK

Each official SDK has a helper that signs a token locally, with no network call: signPlaybackToken in @transcodely/sdk 0.3.27 and later, sign_playback_token in the Python package transcodely 0.3.26 and later, and SignPlaybackToken in transcodely-go v0.3.26 and later. Each takes the key id, the secret and the video id, plus the optional viewer id, lifetime in seconds (60 to 86400, default 14400), overlay text, resolution cap and completion threshold. An input outside the limits in the table above is refused with an error before anything is signed, a viewer id with a control character included.

import { signPlaybackToken } from "@transcodely/sdk";

const token = signPlaybackToken({
  keyId: process.env.TRANSCODELY_PLAYBACK_KEY_ID!,   // psk_…
  secret: process.env.TRANSCODELY_PLAYBACK_SECRET!,  // the whole pss_… string
  videoId: "vid_a1b2c3d4e5f6g7",
  viewerId: "student-8841",
  expiresIn: 14400,
  overlayText: "ana@example.com",
  maxResolution: "1080p",
  completeAt: 0.9,
});
import os
from transcodely import sign_playback_token

token = sign_playback_token(
    key_id=os.environ["TRANSCODELY_PLAYBACK_KEY_ID"],   # psk_…
    secret=os.environ["TRANSCODELY_PLAYBACK_SECRET"],   # the whole pss_… string
    video_id="vid_a1b2c3d4e5f6g7",
    viewer_id="student-8841",
    expires_in=14400,
    overlay_text="ana@example.com",
    max_resolution="1080p",
    complete_at=0.9,
)
completeAt := 0.9
token, err := transcodely.SignPlaybackToken(transcodely.PlaybackTokenParams{
	KeyID:         os.Getenv("TRANSCODELY_PLAYBACK_KEY_ID"), // psk_…
	Secret:        os.Getenv("TRANSCODELY_PLAYBACK_SECRET"), // the whole pss_… string
	VideoID:       "vid_a1b2c3d4e5f6g7",
	ViewerID:      "student-8841",
	ExpiresIn:     14400,
	OverlayText:   "ana@example.com",
	MaxResolution: "1080p",
	CompleteAt:    &completeAt,
})

Without an SDK

The snippets below use each language’s standard library only, for stacks where you would rather not add the SDK. Each one signs exp as whole seconds, cuts overlay text to 80 characters, refuses a viewer id over 128 characters or over 512 bytes once JSON-encoded, and refuses a completion threshold outside 0.1 to 1.0. They do not check a viewer id for control characters: the player page refuses a token whose viewer id has one, so keep line breaks and tabs out of the ids you pass in. The Go function uses the built-in min and max, so it needs Go 1.21 or later.

package playback

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"errors"
	"time"
)

type claims struct {
	VideoID       string   `json:"vid"`
	ViewerID      string   `json:"sub,omitempty"`
	Expires       int64    `json:"exp"`
	OverlayText   string   `json:"ovl,omitempty"`
	CompleteAt    *float64 `json:"cmp,omitempty"`
	MaxResolution string   `json:"mr,omitempty"`
}

// SignPlaybackToken signs a Transcodely playback token locally (no network call).
// The claims are signed, not encrypted: anyone with the URL can read them.
// Pass an empty string (or nil completeAt) for an optional claim you do not use.
func SignPlaybackToken(keyID, secret, videoID, viewerID string, lifetime time.Duration,
	overlayText string, completeAt *float64, maxResolution string, now time.Time) (string, error) {
	// An opaque viewer id of 1 to 128 characters; never an email address or a name.
	if len([]rune(viewerID)) > 128 {
		return "", errors.New("viewer id is over 128 characters")
	}
	// ...and at most 512 bytes JSON-encoded, quotes excluded.
	var sub bytes.Buffer
	enc := json.NewEncoder(&sub)
	enc.SetEscapeHTML(false)
	if err := enc.Encode(viewerID); err != nil {
		return "", err
	}
	if sub.Len()-3 > 512 { // minus the two quotes and the trailing newline
		return "", errors.New("viewer id is over 512 bytes once JSON-encoded")
	}
	// Overlay text: at most 80 characters, longer text is cut.
	if r := []rune(overlayText); len(r) > 80 {
		overlayText = string(r[:80])
	}
	// Server completion threshold: 0.1 to 1.0, 0.9 when nil.
	if completeAt != nil && !(*completeAt >= 0.1 && *completeAt <= 1) {
		return "", errors.New("complete at must be 0.1 to 1.0")
	}
	// Whole seconds, at least 1 and at most 24 hours.
	seconds := int64(lifetime / time.Second)
	seconds = max(1, min(seconds, 86400))

	header, err := json.Marshal(map[string]string{"alg": "HS256", "kid": keyID, "typ": "JWT"})
	if err != nil {
		return "", err
	}
	body, err := json.Marshal(claims{
		VideoID: videoID, ViewerID: viewerID, Expires: now.Unix() + seconds,
		OverlayText: overlayText, CompleteAt: completeAt, MaxResolution: maxResolution,
	})
	if err != nil {
		return "", err
	}
	b64 := base64.RawURLEncoding
	input := b64.EncodeToString(header) + "." + b64.EncodeToString(body)
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(input))
	return "ptk_" + input + "." + b64.EncodeToString(mac.Sum(nil)), nil
}
// Node.js 16+, standard library only.
import { createHmac } from 'node:crypto';

const b64url = (text) => Buffer.from(text, 'utf8').toString('base64url');

// Claims are signed, not encrypted: anyone with the URL can read them.
export function signPlaybackToken({
  keyId, secret, videoId, viewerId, expiresIn = 14400, overlayText, completeAt, maxResolution,
  now = Date.now() / 1000,
}) {
  const header = { alg: 'HS256', kid: keyId, typ: 'JWT' };
  const claims = { vid: videoId };
  if (viewerId) {
    // An opaque id of 1 to 128 characters; never an email address or a name.
    const sub = String(viewerId);
    if ([...sub].length > 128) throw new Error('viewerId is over 128 characters');
    // ...and at most 512 bytes JSON-encoded, quotes excluded. Transcodely's encoder
    // writes U+2028 and U+2029 as 6-byte escapes, so count those 3 bytes extra.
    const escapes = (sub.match(/[

]/g) || []).length;
    if (Buffer.byteLength(JSON.stringify(sub), 'utf8') - 2 + 3 * escapes > 512) {
      throw new Error('viewerId is over 512 bytes once JSON-encoded');
    }
    claims.sub = sub;
  }
  // Whole seconds, at most 24 hours ahead.
  const lifetime = Math.min(Math.max(Math.floor(expiresIn), 1), 86400);
  claims.exp = Math.floor(now) + lifetime;
  // Overlay text: at most 80 characters, longer text is cut.
  if (overlayText) claims.ovl = [...String(overlayText)].slice(0, 80).join('');
  // Share the viewer must play before the server marks the record completed and
  // sends video.viewer.completed: 0.1 to 1.0, 0.9 when left out.
  if (completeAt !== undefined) {
    if (!(completeAt >= 0.1 && completeAt <= 1)) throw new Error('completeAt must be 0.1 to 1.0');
    claims.cmp = completeAt;
  }
  if (maxResolution) claims.mr = maxResolution;
  const input = b64url(JSON.stringify(header)) + '.' + b64url(JSON.stringify(claims));
  const signature = createHmac('sha256', secret).update(input, 'utf8').digest('base64url');
  return 'ptk_' + input + '.' + signature;
}
import base64
import hashlib
import hmac
import json
import time


def _b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")


def sign_playback_token(key_id, secret, video_id, viewer_id=None, expires_in=14400,
                        overlay_text=None, complete_at=None, max_resolution=None, now=None):
    """Signs a Transcodely playback token locally (no network call).

    The claims are signed, not encrypted: anyone with the URL can read them.
    """
    now = int(time.time() if now is None else now)
    header = {"alg": "HS256", "kid": key_id, "typ": "JWT"}
    claims = {"vid": video_id}
    if viewer_id:
        # An opaque id of 1 to 128 characters; never an email address or a name.
        if len(viewer_id) > 128:
            raise ValueError("viewer_id is over 128 characters")
        # ...and at most 512 bytes JSON-encoded, quotes excluded. Transcodely's
        # encoder writes U+2028 and U+2029 as 6-byte escapes: count 3 bytes extra.
        encoded = json.dumps(viewer_id, ensure_ascii=False).encode("utf-8")
        extra = 3 * (viewer_id.count("
") + viewer_id.count("
"))
        if len(encoded) - 2 + extra > 512:
            raise ValueError("viewer_id is over 512 bytes once JSON-encoded")
        claims["sub"] = viewer_id
    # Whole seconds, at most 24 hours ahead.
    claims["exp"] = now + min(max(int(expires_in), 1), 86400)
    if overlay_text:
        # At most 80 characters; longer text is cut.
        claims["ovl"] = overlay_text[:80]
    if complete_at is not None:
        # Server completion threshold: 0.1 to 1.0, 0.9 when left out.
        if not 0.1 <= complete_at <= 1.0:
            raise ValueError("complete_at must be 0.1 to 1.0")
        claims["cmp"] = complete_at
    if max_resolution:
        claims["mr"] = max_resolution

    def encode(obj):
        text = json.dumps(obj, separators=(",", ":"), ensure_ascii=False)
        return _b64url(text.encode("utf-8"))

    signing_input = encode(header) + "." + encode(claims)
    signature = hmac.new(secret.encode("utf-8"), signing_input.encode("utf-8"),
                         hashlib.sha256).digest()
    return "ptk_" + signing_input + "." + _b64url(signature)

Check your own implementation against this test vector. With the signing time fixed at 1800000000 (Unix seconds) and a 4-hour lifetime, it must produce exactly the expected token. The SDK helpers reproduce it too; each takes a clock override for tests: now: () => 1800000000 in JavaScript (a function), now=1800000000 in Python, and Now: time.Unix(1800000000, 0) in Go.

key id         psk_testvector0001
secret         pss_dGVzdC12ZWN0b3Itc2VjcmV0LWRvLW5vdC11c2UtMDE
video id       vid_testvector0001
viewer id      user_8841
overlay text   ana@example.com
max resolution 1080p
expected       ptk_eyJhbGciOiJIUzI1NiIsImtpZCI6InBza190ZXN0dmVjdG9yMDAwMSIsInR5cCI6IkpXVCJ9.eyJ2aWQiOiJ2aWRfdGVzdHZlY3RvcjAwMDEiLCJzdWIiOiJ1c2VyXzg4NDEiLCJleHAiOjE4MDAwMTQ0MDAsIm92bCI6ImFuYUBleGFtcGxlLmNvbSIsIm1yIjoiMTA4MHAifQ.fB9UQjBsfckJGZPX7uILOckTn24-15tnbm7KJq94VVo

The vector has no cmp claim. Its JSON is compact, with the claims in the order vid, sub, exp, ovl, mr. A different order produces a different string that still verifies.

Or let the API sign it

VideoService.CreatePlaybackToken makes the same token in one call. Call it from your server with an API key, never from a browser:

curl -X POST https://api.transcodely.com/transcodely.v1.VideoService/CreatePlaybackToken 
  -H "Authorization: Bearer $TRANSCODELY_API_KEY" 
  -H "Content-Type: application/json" 
  -d '{
    "video_id": "vid_a1b2c3d4e5f6g7",
    "viewer_id": "student-8841",
    "expires_in": 14400,
    "overlay_text": "ana@example.com",
    "complete_at": 0.9,
    "max_resolution": "1080p"
  }'
const minted = await client.videos.createPlaybackToken({
  videoId: "vid_a1b2c3d4e5f6g7",
  viewerId: "student-8841",
  expiresIn: 14400,
});
// minted.token, minted.expiresAt, minted.playerUrl
minted = client.videos.create_playback_token(
    video_id="vid_a1b2c3d4e5f6g7",
    viewer_id="student-8841",
    expires_in=14400,
)
# minted.token, minted.expires_at, minted.player_url
minted, err := client.Videos.CreatePlaybackToken(ctx, &transcodely.VideoCreatePlaybackTokenParams{
	VideoId:   "vid_a1b2c3d4e5f6g7",
	ViewerId:  proto.String("student-8841"),
	ExpiresIn: proto.Int32(14400),
})
// minted.GetToken(), minted.GetExpiresAt(), minted.GetPlayerUrl()
{
  "token": "ptk_eyJhbGciOi…",
  "expires_at": "2026-12-01T14:00:00Z",
  "player_url": "https://play.transcodely.com/v/vid_a1b2c3d4e5f6g7?token=ptk_eyJhbGciOi…"
}
FieldDefaultLimits
video_idrequiredA video of the API key’s app, any visibility.
viewer_idnone1 to 128 characters, no control characters.
expires_in14400 (4 hours)60 to 86400 seconds.
overlay_textnone1 to 80 characters.
complete_at0.90.1 to 1.0. Signed into the token as cmp.
max_resolutionno cap480p, 720p, 1080p, 1440p or 2160p.

The token is signed with the app’s newest active signing key. An app with no key gets one created for it, whose secret is never shown; rotate it from the dashboard if you later want to sign locally. Every field is described in the Videos reference.

Embed it

<iframe id="lesson"
  src="https://play.transcodely.com/v/vid_a1b2c3d4e5f6g7?token=ptk_eyJhbGciOi..."
  allow="autoplay; fullscreen; picture-in-picture" allowfullscreen
  style="width: 100%; aspect-ratio: 16 / 9; border: 0"></iframe>

Make the token on each page load, for the viewer who is signed in. To react to playback and completion from the page, add the player script.


Token lifetime and the stream URLs

The token protects the player page: it decides whether /v/{id} renders. The page then plays the video from CDN URLs that Transcodely signs with a separate secret you never see. For a page opened with a token, those CDN URLs expire at the token’s exp or 6 hours after the page loaded, whichever comes first, so a manifest or segment URL copied out of the page stops working by then.

The consequence: playback that is still running when those URLs expire stops, and the player reports an error event with code expired; reload the page with a fresh token. Make tokens that outlive the lesson plus a pause or two. The default of 4 hours exists for that reason; the maximum is 24 hours.


Allowed embed domains

In the dashboard, open the app, then Playback security, and list the sites allowed to frame its player. Through the API, set allowed_embed_domains with AppService.UpdateHostingConfig:

curl -X POST https://api.transcodely.com/transcodely.v1.AppService/UpdateHostingConfig 
  -H "Authorization: Bearer $TRANSCODELY_API_KEY" 
  -H "Content-Type: application/json" 
  -d '{"id": "app_k1l2m3n4o5", "hosting_config": {"allowed_embed_domains": ["example.com", "*.example.com"]}}'
  • Up to 20 entries. Each is a hostname (example.com, learn.example.co.uk), optionally with a leading *. for any subdomain, optionally with a port (localhost:8080). No scheme, path or query. *.example.com does not include example.com itself: list both.
  • Entries are stored lowercased and de-duplicated. An invalid entry is refused with invalid_argument and a field error on hosting_config.allowed_embed_domains[i].
  • Sending a non-empty list replaces the saved one. Sending an empty list leaves it unchanged. To empty it, send "clear_allowed_embed_domains": true instead.
  • An empty list, the default, means any site may embed the player.

With a list set, every player page of the app (every visibility, with or without a token) is served with a Content-Security-Policy: frame-ancestors header naming those sites over https (and http for localhost and 127.0.0.1), plus the Transcodely dashboard, so the previews in your dashboard keep working. Browsers then refuse to show it in a frame anywhere else. Cached public guide pages can take up to 5 minutes to pick up a change. A private video opened directly, outside a frame, shows “This video can only be watched on the site it belongs to” with status 403.

Add every host your pages are served from, including the www. form if you use it.


Overlay and resolution cap

Overlay. With ovl set, the player draws the text over the video, semi-transparent, and moves it to a new position every 15 to 25 seconds. It stays on screen when the viewer uses the player’s fullscreen button. It cannot show in the iPhone’s native video fullscreen, where Safari hands the video to the system player. Use something that identifies the viewer to themselves, such as their email address, so a screen recording carries it.

Resolution cap. With mr set, the player never selects a rendition above that size, for example to keep a preview tier at 720p. The cap compares each rendition’s short side, so 1080p keeps a portrait 1080×1920 rendition. It has no effect where the browser plays HLS natively (Safari, and every browser on iOS), because there the browser, not the player, picks the rendition.


What this protects against, and what it does not

Protected playback makes casual sharing hard and visible. It is not DRM.

It does:

  • keep private videos off the hosted player for anyone without a valid token,
  • tie each token to one video and one app, with an expiry of at most 24 hours,
  • stop copied stream URLs from working past the token’s expiry (or 6 hours after the page loaded, if sooner),
  • keep the player off sites that are not on your allowed list,
  • put the viewer’s own identifier on screen when you set an overlay.

It does not:

  • Stop a viewer sharing their token. Anyone with a valid token can watch until it expires. Keep lifetimes short and rotate the key if a token leaks.
  • Stop saving or recording. The viewer’s browser receives the video segments it plays and can save them; a screen recorder sees what the screen shows.
  • Make the overlay permanent. It is a visible deterrent drawn by the player, and a determined person can remove it. It is not forensic (invisible) watermarking and it is not burned into the video.
  • Enforce the resolution cap everywhere. mr is applied by the player when it picks renditions, not by the CDN, and not at all where the browser plays HLS natively (Safari and iOS). Someone who extracts the manifest can request higher renditions until the stream URLs expire.
  • Hide what the token says. The claims are readable by anyone with the URL, and URLs can be recorded in request logs.
  • Revoke one token. Rotating the signing key immediately is the only revocation, and it revokes every token that key signed. It also only stops new page loads: a player already open keeps playing until its stream URLs expire, at most 6 hours after it loaded.
  • Show the overlay in iOS native fullscreen. When an iPhone plays the video in the system’s own fullscreen player, the overlay is not visible.
  • Provide DRM. Hosted videos are not encrypted with Widevine, FairPlay or PlayReady.

Next steps

Run this against your own file

A free account runs standard-quality encodes up to 2 minutes, one at a time (a longer upload is shortened to its first 2 minutes), so the Quickstart runs with nothing set up but an API key.