Sub topic 14
Protecting content: signed URLs and DRM
This chapter assumes you know HTTP and caching, how a CDN serves objects from an origin, and how HLS segments and playlists are laid out. It builds on the packaging and CDN chapters. It covers how to control who can fetch your video and what they can do with it after they have it.
Two different problems
Content protection is two problems that people often mix up.
- Access control decides who may download the bytes. Signed URLs, tokens, and cookies solve this.
- Content protection after delivery decides what a client can do with the bytes it received. Encryption and DRM (digital rights management) solve this.
A signed URL stops a stranger from fetching your segments. It does nothing once an authorized user has saved them. DRM keeps the segments encrypted on the wire and on disk, and releases the decryption key only to a trusted player under rules you set. Most platforms need the first. Only those with licensed or premium content usually need the second.
| Layer | Question it answers | Typical tool | Stops hotlinking | Stops copying |
|---|---|---|---|---|
| Authentication | Who is this user? | Session, OAuth token | No | No |
| Authorization | May this user watch this title? | Entitlement check in API | No | No |
| Signed URL or cookie | May this request hit the CDN? | HMAC token | Yes | No |
| Encryption (AES-128) | Can a bystander read the bytes? | HLS key file | Partly | No |
| DRM | Can the player use the bytes under our rules? | Widevine, FairPlay, PlayReady | Yes | Raises the bar |
Threat model first
Decide what you defend against before choosing tools.
- Hotlinking: another site embeds your URLs and you pay for their traffic.
- Link sharing: a paying user posts a playback URL, and anyone can use it.
- Scraping: a script walks your catalog and downloads every segment.
- Stream ripping: a legitimate client records the decoded output or captures the segments.
- Key leakage: the decryption key is exposed or reused across titles.
No scheme fully stops ripping. A person can always film the screen. DRM makes casual ripping hard and gives studios the contractual assurance they demand. It does not make it impossible.
Signed URLs
A signed URL carries a token proving that your backend approved this request. The CDN verifies it at the edge, so the request never reaches your origin or API.
The usual construction is an HMAC (a keyed hash) over the path and an expiry time, using a secret shared between your backend and the CDN.
import base64
import hashlib
import hmac
import time
def sign_url(path: str, secret: bytes, ttl_seconds: int = 300) -> str:
"""Return a path with an expiry and an HMAC-SHA256 signature."""
expires = int(time.time()) + ttl_seconds
message = f"{path}:{expires}".encode()
digest = hmac.new(secret, message, hashlib.sha256).digest()
sig = base64.urlsafe_b64encode(digest).decode().rstrip("=")
return f"{path}?expires={expires}&sig={sig}"
def verify_url(path: str, expires: int, sig: str, secret: bytes) -> bool:
if expires < time.time():
return False
message = f"{path}:{expires}".encode()
digest = hmac.new(secret, message, hashlib.sha256).digest()
expected = base64.urlsafe_b64encode(digest).decode().rstrip("=")
return hmac.compare_digest(expected, sig)
secret = b"replace-with-a-random-32-byte-secret"
url = sign_url("/video/abc123/720p/index.m3u8", secret)
print(url)
path, query = url.split("?")
params = dict(p.split("=", 1) for p in query.split("&"))
print(verify_url(path, int(params["expires"]), params["sig"], secret)) # TrueTwo details matter. Use hmac.compare_digest rather than == so comparison time does not leak information about the signature. Keep the secret in a secrets manager, never in the repository.
Real CDNs have their own formats, such as CloudFront signed URLs, Akamai tokens, and Fastly or Cloudflare token authentication. The idea is the same. Use the CDN's native feature so verification happens at the edge.
The playlist problem
A video is not one URL. A playback session fetches a master playlist, a media playlist, and hundreds of segments. Signing every one is awkward. A media playlist lists relative segment names, so a player resolves them against the playlist URL. The query string on the playlist does not carry over to those segment requests.
You have three ways to handle this.
- Rewrite playlists per user. Your backend generates each media playlist with signed segment URLs. This is flexible but moves playlist traffic off the CDN cache and onto your servers.
- Sign a path prefix. The token authorizes everything under
/video/abc123/*until it expires. One signature covers the whole session. - Use signed cookies. The backend sets a cookie scoped to the video path. The CDN checks it on every request, and the URLs stay clean and cacheable.
Prefix tokens and signed cookies are the common choices for video. Signed cookies fit best when the player and CDN share a domain.
Do not use that block. The diagram below shows the real flow.
Caching and token design
Tokens can break caching. If the token is part of the cache key, every user gets a distinct cache entry and your hit ratio drops to near zero. Configure the CDN so that the signature and expiry query parameters are validated but excluded from the cache key. The cache key then contains only the path, and all users share cached segments.
Choose lifetimes with playback in mind.
- A token that expires in 30 seconds breaks a viewer who pauses and resumes, or whose player prefetches segments late.
- A token that lasts 24 hours is effectively a shareable link.
- A typical choice is a few minutes for the first request, with the player refreshing the token through your API before it lapses. For long films, a lifetime longer than the runtime plus a margin is simpler.
Additional restrictions can narrow the damage of a leaked link: bind the token to an IP range, a user agent, or a user ID that you log. IP binding causes false rejections when a phone moves between Wi-Fi and mobile data, so use it only where that risk is acceptable.
Encrypting segments
HLS supports AES-128 encryption of segments. The media playlist points to a key URL, and the player fetches the key and decrypts each segment.
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:4
#EXT-X-KEY:METHOD=AES-128,URI="https://keys.example.com/k/abc123",IV=0x00000000000000000000000000000001
#EXTINF:4.000,
seg_0000.ts
#EXTINF:4.000,
seg_0001.ts
#EXT-X-ENDLISTThis protects segments sitting in storage and on caches. The weakness is the key URL. Any client that can fetch the key can decrypt everything, and nothing stops it from saving the key. Serve the key only from an authenticated endpoint, never cache it publicly, and use a distinct key per title.
Plain AES-128 is therefore protection against casual access, not rights enforcement.
DRM
DRM adds a license server and a trusted component in the player. The content is encrypted once, and the key is delivered inside a license that the device's secure module handles. The key is not exposed to page JavaScript or to the user.
Three systems cover nearly all devices.
| System | Vendor | Main platforms |
|---|---|---|
| Widevine | Chrome, Android, many smart TVs | |
| FairPlay | Apple | Safari, iOS, tvOS |
| PlayReady | Microsoft | Edge, Xbox, many smart TVs |
Packaging once for all three uses CENC (Common Encryption), a standard that lets the same encrypted media work with multiple DRM systems. It is used with fragmented MP4 (CMAF) segments. Apple devices historically needed a different mode, cbcs, and modern practice is to encrypt with cbcs so one set of files serves every system. Check the support matrix of your target devices before committing.
The playback flow adds a license exchange.
- The player reads the manifest and finds the encryption metadata (the key ID and DRM system identifiers).
- The browser's Encrypted Media Extensions (EME) API creates a license request through the device's content decryption module.
- The player sends that request, with the user's token, to your license server.
- The license server checks entitlement and returns a license containing the key and the rules: expiry, output restrictions, offline permission.
- The decryption module decrypts and renders frames. Page code never sees the key.
Most teams buy a multi-DRM service rather than build license servers, because each vendor requires certification and secure key handling. Building your own is rarely worthwhile.
Policy decisions
Resolution can be tied to security level. Widevine defines levels where L1 uses hardware-protected decryption and L3 uses software. Studios commonly allow HD and 4K only on L1 devices and cap L3 devices at SD. Your license server enforces this by issuing different license rules based on the device's reported level.
Other rules the license can carry include concurrent stream limits, rental windows, and offline download expiry. Concurrency limits need a session store that the license or playback API updates, since the CDN cannot count streams.
Common errors
- Token in the cache key. Hit ratio collapses and origin load spikes. Exclude it from the key.
- Signing only the playlist. Segment URLs are unsigned, so anyone with a segment path bypasses protection.
- Clock skew. Expiry checks use time. Keep servers synchronized and allow a small tolerance.
- One key for the whole catalog. A single leak exposes everything. Use per-title keys, or per-title-and-quality keys.
- Public key endpoint. AES-128 keys served without authentication make encryption pointless.
- Treating DRM as access control. DRM does not stop hotlinking or scraping of encrypted bytes. Use signed URLs as well.
- Long-lived origin exposure. If the origin bucket is public, the CDN checks are bypassed. Restrict the bucket so only the CDN can read it.
Choosing a level
- User-generated, free content: signed URLs or cookies, short tokens, locked-down origin. No encryption needed.
- Subscription content with light concerns: add AES-128 with an authenticated key endpoint.
- Licensed studio content: multi-DRM with
cbcs, security-level rules, and the contract's output restrictions.
Each step adds cost: more integration work, more device testing, and more failure points that show up as playback errors. Pick the lowest level that meets your contractual and business needs.
Exercise
A team signs only the media playlist URL with a 5-minute expiry. Segment URLs inside the playlist are unsigned relative paths. Name the weakness, and give two ways to fix it that keep CDN cache hit ratios high.
Show answer
Anyone who learns or guesses a segment path can fetch it with no token, so the signature protects only the playlist. Fixes: (1) issue a signed cookie scoped to the video path prefix, or a prefix token that covers all objects under that path, and have the CDN validate it on every request; (2) validate the token at the edge for segments as well, with the signature and expiry excluded from the cache key so all users share cached segments. Rewriting per-user playlists with signed segment URLs also works but moves playlist traffic off the cache.
Exercise
Why does AES-128 HLS encryption not stop a paying user from sharing a video, while DRM makes it harder?
Show answer
With AES-128 the player fetches the key from a URL and holds it in ordinary memory, so the user can save the key and the segments and decrypt them elsewhere. With DRM the key is delivered in a license to a secure decryption module on the device. Page code and the user never see it, and the license can restrict output and expire. Screen recording is still possible, so DRM raises the cost of copying but does not eliminate it.