In Cloudflare Stream, how do requireSignedURLs and signed tokens keep paid lessons playable only by enrolled students?
answer
- public by video ID until changed
- the token takes the ID's place
- sign locally with a key
- exp no more than a day
- allowedOrigins against hotlinking
basics
~20 sSetting requireSignedURLs on a Stream video stops its bare ID from playing anywhere. Your backend checks enrolment, then issues a signed token that replaces the video ID in the player or manifest URL until its exp passes.
solid answer
~40 sTurn on `requireSignedURLs` for each paid lesson, ideally at upload; the watch page, iframe and manifests then refuse the bare video ID. When an enrolled student opens a lesson, your backend checks enrolment and returns a token, which takes the ID's place in `customer-<CODE>.cloudflarestream.com/<TOKEN>/iframe` or `/manifest/video.m3u8`. You can mint tokens three ways: the `/token` endpoint (one API call per token, rate-limited, one hour by default), the Workers binding's `generateToken()`, or, at scale, a **signing key** from `/stream/keys` used to sign an RS256 token yourself with `sub`, `kid` and an `exp` at most 24 hours out, plus optional `accessRules` or `downloadable`. Add `allowedOrigins` so even a valid token plays only on your domains.
code
javascript · 41 linesimport { isEnrolled } from "./enrollment.js";
const enc = new TextEncoder();
const b64url = (bytes) =>
btoa(String.fromCharCode(...new Uint8Array(bytes)))
.replace(/=+$/, "")
.replace(/\+/g, "-")
.replace(/\//g, "_");
const b64urlJson = (obj) => b64url(enc.encode(JSON.stringify(obj)));
async function signStreamToken(env, videoUid, ttlSeconds) {
const header = { alg: "RS256", kid: env.STREAM_KEY_ID };
const payload = {
sub: videoUid,
kid: env.STREAM_KEY_ID,
exp: Math.floor(Date.now() / 1000) + ttlSeconds,
};
const unsigned = `${b64urlJson(header)}.${b64urlJson(payload)}`;
const key = await crypto.subtle.importKey(
"jwk",
JSON.parse(atob(env.STREAM_JWK)),
{ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
false,
["sign"],
);
const sig = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, enc.encode(unsigned));
return `${unsigned}.${b64url(sig)}`;
}
export default {
async fetch(request, env) {
const videoUid = new URL(request.url).searchParams.get("lesson");
if (!videoUid || !(await isEnrolled(request, env, videoUid))) {
return new Response("Forbidden", { status: 403 });
}
const token = await signStreamToken(env, videoUid, 4 * 60 * 60);
return Response.json({
iframe: `https://customer-${env.STREAM_CUSTOMER_CODE}.cloudflarestream.com/${token}/iframe`,
});
},
};go deeper
Recall that Stream videos are public by ID until requireSignedURLs is set, and that a token replaces the ID in the URL.
Explain the three ways to mint tokens, the sub, kid and exp claims, the 24-hour cap, and what allowedOrigins adds.
Show the production setup: private at upload, enrolment checked before signing, short exp, keys stored as secrets, and revocation ready for a leak.
Decide how strict access should be: token lifetime, geo or IP rules and download rights trade student friction against how far a shared link can travel.
## Public by default A Stream video is **public by default**: anyone who knows its video ID can open `customer-<CODE>.cloudflarestream.com/<VIDEO_ID>/watch`, embed the `/iframe` player or point any HLS or DASH player at `/manifest/video.m3u8` or `/manifest/video.mpd`. Video IDs end up in page source, browser history and shared links, so an obscure ID is not access control. A course platform that sells lessons needs two things: lessons that refuse to play by ID, and a way to admit enrolled students one at a time. ## Making a lesson private Set **`requireSignedURLs`** to `true` on each paid video. Once set, every public link stops working, including the watch page, the built-in player, the manifests, thumbnails used as a player `poster`, and MP4 downloads. It can be set: - at upload time: the `requireSignedURLs` field of a direct upload, or the bare `requiresignedurls` key in tus `Upload-Metadata`; - later, by editing the video through `.../stream/{video_uid}` with `{"uid": "...", "requireSignedURLs": true}`; - from a Worker with `env.STREAM.video(id).update({ requireSignedURLs: true })`. Setting it at upload time is safer: the lesson is never public, even for the minutes between upload and a later update. ## Three ways to mint a token | Method | How | Best for | |---|---|---| | `/token` endpoint | `POST .../stream/{video_uid}/token` with the API token | Testing or under about 1,000 tokens a day; one API call per token, rate-limited, valid one hour by default | | Workers binding | `env.STREAM.video(id).generateToken()` | Workers code wanting no key management; one-hour default, no custom claims | | **Signing key** | Create once with `POST .../stream/keys`, then sign tokens yourself | Production volume and custom restrictions; no API call per token | The signing-key response contains an `id`, plus `pem` and `jwk` forms of the private key, both base64-encoded. They are shown **once**, so store them immediately as secrets. Your backend then signs an **RS256** JSON Web Token whose header names the key's `kid`. ## The token's claims - `sub`: the ID of the video the token admits. - `kid`: the signing key's ID. - `exp`: a Unix timestamp after which the token stops working; it may be **at most 24 hours** after signing. - `nbf`: an optional time before which the token does not work. - `downloadable`: `true` lets the token fetch the MP4 download, if downloads are enabled on the video. - `accessRules`: up to **five** rules, evaluated first to last; the first match applies its action and stops. Each has a `type` of `any`, `ip.src` or `ip.geoip.country` and an `action` of `allow` or `block`. A final `{"type": "any", "action": "block"}` turns the list into an allow-list. Access rules are checked **continuously** during playback, so narrow IP rules can cut off a student whose phone changes IP mid-lesson; prefer CIDR ranges and include IPv4 and IPv6 forms. ## Where the token goes The token **replaces the video ID** in the URL, nothing else changes: 1. Player: `https://customer-<CODE>.cloudflarestream.com/<TOKEN>/iframe` 2. Your own player: `.../<TOKEN>/manifest/video.m3u8` or `.../<TOKEN>/manifest/video.mpd` 3. Download (with `downloadable: true`): `.../<TOKEN>/downloads/default.mp4` 4. Thumbnail: `.../<TOKEN>/thumbnails/thumbnail.jpg`, since a private video's thumbnail also needs the token The `/token` endpoint can take the same restrictions in its request body (`exp`, `downloadable`, `accessRules`), but every such call is a rate-limited API request, so a service that customises tokens per student is the case the signing key exists for. The flow is: the student opens a lesson, your backend checks enrolment in its own database, signs a token with a short `exp` that covers one viewing session, and returns the player URL. A token is a bearer credential until it expires, which is why `exp` should be hours, not the full 24. ## allowedOrigins and key hygiene - **`allowedOrigins`** limits which sites may embed a video, and with your own player it limits which origins may request its manifests and segments. Combined with signed URLs, a leaked token cannot simply be pasted into another site's player. Rules are exact: `example.com` does not cover `www.example.com`, while `*.example.com` covers subdomains but not the apex. - An account can hold up to **1,000 signing keys**. Revoking one with `DELETE .../stream/keys/{key_id}` invalidates **every token** it signed, which is the response to a leaked key. JWT structure and signature algorithms in general are covered with JSON Web Tokens; what Stream adds is which claims it reads, the 24-hour cap, and where the token sits in the URL.
- What do accessRules add to a Stream token, and what is the catch with IP rules?Up to five rules of type `any`, `ip.src` or `ip.geoip.country` with `allow` or `block`, evaluated in order with the first match winning; ending with `any` plus `block` makes an allow-list. Rules are checked continuously during playback, so a strict IP rule can stop a lesson when a phone's address changes.
- A Stream signing key's JWK leaks from a config repository. What do you do?Create a new key with `POST .../stream/keys`, store its `id` and `jwk` as secrets and redeploy the token service, then revoke the leaked key with `DELETE .../stream/keys/{key_id}`. Revocation invalidates every token that key signed, so students simply get fresh tokens from the new key.
- Does requireSignedURLs also cover a lesson's MP4 download and thumbnail?Yes. A private video's MP4 download works only with a token carrying `downloadable: true` (and downloads enabled on the video), and a player `poster` thumbnail must use a signed URL instead of the video ID.
- Keeping the video ID out of page source is enough to make a lesson private.
- allowedOrigins alone stops non-students watching on your own site.
- A signed Stream token can be set to last a week.
- Calling the /token endpoint per view scales to thousands of students.
- The signing key's jwk can be fetched again from the API later.
- The token goes in an Authorization header on manifest requests.
Assumes Stream as of 2026-10-10: tokens can also come from the Workers Stream binding's generateToken(), added in May 2026, beside the /token endpoint and signing keys.