Sub topic 14
Controlling who can fetch media: signed URLs and signed cookies
This chapter assumes you know HTTP headers and cookies, the CDN caching model from the previous chapters, and the idea of presigned URLs for uploads. It covers how to keep private media private without giving up CDN caching.
The problem: a URL is a capability
Public media is simple. Anyone with the URL can fetch it, and the CDN caches it. Private media, such as paid videos, invoices, or a user's photos, needs a check before each fetch. If your API server performs that check and streams the bytes, you lose the benefits of object storage and the CDN. Every download passes through your servers.
Signed URLs and signed cookies solve this by moving the decision earlier. Your application decides once, at page-render or API time, whether a user may see a file. It then issues a short-lived proof of that decision. The CDN or storage service verifies the proof cryptographically and serves the bytes without calling your application.
Options compared
| Approach | Who checks access | Cache friendliness | Best for |
|---|---|---|---|
| Public URL with unguessable key | Nobody | Excellent | Low-sensitivity content such as public avatars |
| Signed URL | CDN or storage edge verifies a signature | Good, if the signature is not part of the cache key | A single file: download links, images in a page |
| Signed cookie | CDN verifies the cookie | Good | Many files: HLS playlists and segments, a gallery |
| Authorizing proxy | Your application on every request | Poor | Rules that change per request, or that need a database lookup |
An unguessable key is not access control. Keys leak through logs, referrer headers, browser history, and shared links. Treat them as identifiers, not secrets.
How a signature works
A signed URL carries three things: what is allowed (a path or pattern), until when (an expiry timestamp), and a signature over both. The verifier recomputes the signature with a key it holds. If the values match and the time has not passed, it serves the file.
There are two signing styles:
- Symmetric (HMAC): the signer and verifier share a secret. This is simple, and it works when you control the verifier, for example an edge function or a reverse proxy.
- Asymmetric (RSA): the signer holds a private key and the CDN holds the public key. CloudFront signed URLs work this way. A compromised CDN configuration cannot be used to mint new URLs.
A signed URL you can run
This example uses an HMAC so you can see the mechanics. In production you would normally use your CDN's built-in verification, but the checks are the same.
import base64
import hashlib
import hmac
import time
from urllib.parse import urlencode
SECRET = b"replace-with-a-secret-from-your-vault"
def _mac(path: str, expires: int) -> str:
message = f"{path}\n{expires}".encode()
digest = hmac.new(SECRET, message, hashlib.sha256).digest()
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
def sign_path(path: str, ttl: int = 300, now: float | None = None) -> str:
current = time.time() if now is None else now
expires = int(current) + ttl
query = urlencode({"exp": expires, "sig": _mac(path, expires)})
return f"{path}?{query}"
def verify(path: str, exp: str, sig: str, now: float | None = None) -> bool:
current = time.time() if now is None else now
try:
expires = int(exp)
except ValueError:
return False
if expires < current:
return False
return hmac.compare_digest(_mac(path, expires), sig)
if __name__ == "__main__":
url = sign_path("/media/42/poster.webp", ttl=300, now=1_000_000)
print(url)
path, query = url.split("?")
params = dict(p.split("=") for p in query.split("&"))
print(verify(path, params["exp"], params["sig"], now=1_000_100)) # True
print(verify(path, params["exp"], params["sig"], now=1_000_400)) # False, expired
print(verify("/media/43/poster.webp", params["exp"], params["sig"], now=1_000_100)) # False, other pathThree details matter here:
- The signature covers the path, so a URL for one file cannot be reused for another.
hmac.compare_digestcompares in constant time, which avoids leaking information through timing.- The expiry is part of the signed message. If it were only a plain parameter, a client could edit it.
Signed URLs directly from storage
If you do not use a CDN for a given file, the storage service can verify the signature. With S3, a presigned GET URL works like the upload URLs from earlier chapters. You can also set response headers that control download behavior.
import boto3
s3 = boto3.client("s3")
url = s3.generate_presigned_url(
"get_object",
Params={
"Bucket": "example-uploads",
"Key": "invoices/2026/11/inv-1001.pdf",
"ResponseContentDisposition": 'attachment; filename="invoice-1001.pdf"',
"ResponseContentType": "application/pdf",
},
ExpiresIn=120,
)The ResponseContentDisposition value is part of the signature. The client cannot change it to make a browser render the file inline.
Signed cookies for many files
A signed URL authorizes one URL. That is awkward for HLS video. A playlist (.m3u8) refers to dozens or hundreds of segment files by relative path. Query parameters on the playlist URL are not copied onto the segment requests, so each segment would need its own signed URL. You would have to rewrite the playlist for every viewer, which defeats playlist caching.
Signed cookies fix this. The browser sends the cookie with every request to the media domain. A single policy can cover a wildcard such as /media/42/*.
HTTP/1.1 200 OK
Set-Cookie: CloudFront-Policy=eyJTdGF0ZW1lbnQiOi4uLn0_; Domain=media.example.com; Path=/media/42/; Secure; HttpOnly; SameSite=Lax; Max-Age=3600
Set-Cookie: CloudFront-Signature=aBcD...; Domain=media.example.com; Path=/media/42/; Secure; HttpOnly; SameSite=Lax; Max-Age=3600
Set-Cookie: CloudFront-Key-Pair-Id=K2JCJMDEHXQW5F; Domain=media.example.com; Path=/media/42/; Secure; HttpOnly; SameSite=Lax; Max-Age=3600Rules for cookies:
- The media domain must share a registrable domain with the site that sets the cookie (for example
app.example.comandmedia.example.com), andDomainmust be set accordingly. - Use
SecureandHttpOnlyso scripts cannot read the cookie. Note that a video player usingfetchorXMLHttpRequestacross origins must also enable credentials, and the CDN must send matching CORS headers. - Match the
Max-Ageto the policy expiry, so the browser stops sending a cookie that is already invalid.
Choosing between them
Use a signed URL when one file is requested, when the link will be shared outside a browser session (an email link), or when the client is not a browser. Use signed cookies when a page or player loads many related files, or when you do not want to modify URLs in manifests or HTML. You can combine both: cookies for the video player and a signed URL for the "download original" button.
Caching and expiry
A signed URL is unique per issuance, because its signature and expiry change. If the CDN includes the query string in its cache key, every viewer gets a separate cache entry and the hit rate drops to near zero. Configure the CDN so that signature parameters are verified at the edge but excluded from the cache key. CloudFront does this for signed URLs and cookies. For a custom edge function, remove exp and sig from the key.
One consequence follows from this. A cached object is served to anyone whose signature verifies, and verification happens on every request. Caching does not bypass access control, but you must make sure the verification step runs before the cache lookup.
Choose expiry by the use case:
- Page images and thumbnails: a few minutes to an hour. Round the expiry to a fixed boundary, such as the next hour, so repeated page renders produce the same URL and browsers can reuse their cache.
- Downloads: one to five minutes, since the click follows immediately.
- Video playback: the length of the video plus a margin, preferably refreshed by the player with a new cookie.
Gotchas
- Revocation is weak. A valid URL works until it expires, even if the user loses access a second later. Keep expiries short, and for urgent revocation, rotate the signing key or delete the object.
- Leaked URLs are usable by anyone until they expire. Avoid putting them in logs, analytics events, and third-party referrer headers. A
Referrer-Policy: no-referrerheader on pages that embed private media helps. - Clock skew causes spurious failures. Issue URLs with a short grace period at the start if your signers and verifiers disagree on time, and keep the servers synchronized with NTP.
- Block direct access to the origin. Restrict the bucket so only the CDN can read it (for example with origin access control). Otherwise people can bypass signature checks by calling storage directly.
- Sign the narrowest scope that works. A wildcard policy for
/*turns a viewing grant into a grant for the whole bucket. - Serve user content from a separate domain with safe headers, as the next chapter explains. Access control decides who can fetch a file. It does not make an attacker's HTML file safe to render.
Exercise
A video site serves HLS streams. The team signs the URL of each playlist (/media/42/index.m3u8?exp=...&sig=...), but playback fails when the player requests /media/42/seg-001.ts. Why does it fail, and what is a fix that keeps the playlist and segments cacheable?
Show answer
The segment requests use relative paths from the playlist, so the exp and sig query parameters are not carried over, and the CDN rejects the unsigned segment requests. The fix is to use signed cookies with a policy covering /media/42/*. The browser sends the cookie on the playlist and every segment request, the playlist can be cached without per-viewer rewriting, and signature parameters stay out of the cache key. The media domain must share a registrable domain with the site, and the cookie must be Secure and HttpOnly.
Exercise
In the HMAC example, what attack becomes possible if the signed message contains only the expiry and not the path?
Show answer
A user with a valid URL for one file could reuse the same exp and sig values with any other path, because the signature would not depend on which file was requested. Including the path in the signed message ties each signature to a single file.