Sub topic 14
Restricting private content with signed URLs and cookies
This chapter covers how to make CloudFront serve some objects only to viewers who hold a valid signature. It assumes you can read the distribution and cache behavior setup from earlier chapters. You should also be comfortable with OAC, the HTTP Cookie header, and running the AWS CLI and OpenSSL. Python knowledge is helpful for the signing example.
What OAC does and does not protect
Origin Access Control keeps viewers from bypassing CloudFront and reading the bucket directly. It does not decide which viewers may read through CloudFront. With only OAC, anyone who knows a URL on the distribution gets the object.
Signed URLs and signed cookies add that second check. You hold a private key and sign a statement such as "this resource, until this time." CloudFront holds the matching public key. Each edge location checks the signature before it serves a response, including a response from cache.
The two controls are independent, and a private setup usually uses both:
| Layer | Question it answers | Mechanism |
|---|---|---|
| Origin protection | Can anyone reach S3 without CloudFront? | OAC and bucket policy |
| Viewer protection | Can this viewer read this object through CloudFront? | Signed URLs or signed cookies |
How a signed request flows
Your application decides who is allowed. It signs a URL or sets cookies, and the viewer sends them with the request. CloudFront verifies them at the edge.
CloudFront never learns who the viewer is. It only checks that the signature is valid, so the authorization decision stays in your application.
Choosing between signed URLs and signed cookies
Both use the same keys and the same behavior setting. They differ in how the proof reaches CloudFront.
| Use | Signed URLs | Signed cookies |
|---|---|---|
| One file, such as a download link | Good fit | Works, but heavier |
| Many files, such as an HLS video with many segments | Each URL needs its own signature | Good fit, one grant covers a path pattern |
| Clients that do not support cookies | Required | Not usable |
| Keep the visible URLs unchanged | No, the URL carries the signature | Yes |
| Link is shared by pasting it | The signature travels with the link | The link alone is useless |
If both a signed URL and signed cookies are present on a request, CloudFront uses the signed URL.
Create the key pair and key group
CloudFront accepts RSA keys of 2048 bits. You create the pair yourself and upload only the public half. Keep the private key in a secrets store, never in the repository or the bucket.
openssl genrsa -out private_key.pem 2048
openssl rsa -pubout -in private_key.pem -out public_key.pem
jq -n --rawfile key public_key.pem \
'{CallerReference:"site-key-1",Name:"site-key-1",EncodedKey:$key}' \
> public-key-config.json
aws cloudfront create-public-key --public-key-config file://public-key-config.jsonThe response contains the public key Id. This is the value you later pass as the key pair ID when signing. Put the key into a key group:
aws cloudfront create-key-group \
--key-group-config Name=site-key-group,Items=K2JCJMDEHXQW5FReplace K2JCJMDEHXQW5F with your own public key ID. A key group can hold several public keys, and that is how you rotate keys. Add the new key, switch your signer to it, wait until URLs signed with the old key have expired, then remove the old key.
Require signatures on a cache behavior
A key group only takes effect when a cache behavior names it as a trusted key group. Restrict the path pattern that holds private content and leave public paths open. This avoids signing assets such as CSS files.
Parameters:
KeyGroupId:
Type: String
Resources:
SiteDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Enabled: true
DefaultRootObject: index.html
Origins:
- Id: s3-origin
DomainName: !GetAtt SiteBucket.RegionalDomainName
OriginAccessControlId: !GetAtt SiteOac.Id
S3OriginConfig:
OriginAccessIdentity: ''
DefaultCacheBehavior:
TargetOriginId: s3-origin
ViewerProtocolPolicy: redirect-to-https
CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6
CacheBehaviors:
- PathPattern: private/*
TargetOriginId: s3-origin
ViewerProtocolPolicy: https-only
CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6
TrustedKeyGroups:
- !Ref KeyGroupIdThis excerpt assumes SiteBucket and SiteOac exist, as in the earlier chapters. With TrustedKeyGroups set, every request to /private/* without a valid signature gets a 403 from the edge. The request never reaches S3.
Canned and custom policies
A policy states what the signature allows. CloudFront supports two kinds.
- Canned policy. It covers one exact URL with an expiry time. The URL carries
Expires,Signature, andKey-Pair-Id. It is the shortest form and the right default for single-file links. - Custom policy. It is a JSON document that can use a wildcard in the resource and can add a start time (
DateGreaterThan) and a viewer IP range (IpAddress). The URL carriesPolicy,Signature, andKey-Pair-Id. Signed cookies commonly use this form, because one wildcard covers many files.
The expiry is required in every policy. Choose it from the use case. A few minutes suits a download link, and the length of a session suits a streaming grant.
Sign a URL in code
The AWS CLI can sign a canned-policy URL for testing:
aws cloudfront sign \
--url "https://d111111abcdef8.cloudfront.net/private/report.pdf" \
--key-pair-id K2JCJMDEHXQW5F \
--private-key file://private_key.pem \
--date-less-than 2026-12-01T00:00:00ZIn an application, use the signer in botocore. It needs a function that signs a message with RSA and SHA-1, which is what CloudFront requires for the signature. The example uses the cryptography package.
import datetime
from botocore.signers import CloudFrontSigner
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
KEY_PAIR_ID = "K2JCJMDEHXQW5F"
def rsa_signer(message: bytes) -> bytes:
with open("private_key.pem", "rb") as f:
key = serialization.load_pem_private_key(f.read(), password=None)
return key.sign(message, padding.PKCS1v15(), hashes.SHA1())
signer = CloudFrontSigner(KEY_PAIR_ID, rsa_signer)
expires = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=10)
# Canned policy: one exact URL
url = "https://d111111abcdef8.cloudfront.net/private/report.pdf"
print(signer.generate_presigned_url(url, date_less_than=expires))
# Custom policy: wildcard resource, restricted to one IP range
policy = signer.build_policy(
"https://d111111abcdef8.cloudfront.net/private/*",
date_less_than=expires,
ip_address="203.0.113.0/24",
)
print(signer.generate_presigned_url(url, policy=policy))The first call produces a URL signed against the exact object. The second signs against the wildcard policy, so the same signature would also work for other paths under /private/.
For signed cookies, you compute the same signature and return it as three Set-Cookie headers: CloudFront-Policy (or CloudFront-Expires for a canned policy), CloudFront-Signature, and CloudFront-Key-Pair-Id. The CloudFront documentation gives the exact encoding of the policy and signature values.
Gotchas and common errors
- 403 with a correct-looking URL. Check that the key pair ID is the public key's
Id, not the key group ID. Check that the key is in a key group attached to the matching behavior. Check that the behavior's path pattern covers the requested path. - Clock and expiry. Expiry is compared with the edge's clock. Generate expiry from UTC and avoid tiny lifetimes that network delay can consume.
- Signature parameters and caching. Signing parameters do not make each URL a separate cache entry. Two viewers with different valid signatures for the same object can hit the same cached copy. Other query strings still follow your cache policy.
- Cookie scope. Signed cookies are sent only to the domain that set them. Serve the application and the content from the same parent domain, which means using a custom domain, or the browser will not send the cookies.
- Do not mix up the two features. The older S3 presigned URLs sign requests to S3. CloudFront signed URLs use a separate key pair and are checked by CloudFront. Signing for S3 does not protect a CloudFront path.
Exercise
A video site serves 400 HLS segment files per video under /videos/abc/. Users log in, then watch for up to two hours. Would you use signed URLs or signed cookies, and which policy type? Name two settings you must configure on the distribution for it to work.
Show answer
Use signed cookies with a custom policy. One wildcard resource such as /videos/abc/ and an expiry of about two hours covers every segment without signing 400 URLs or rewriting the playlist. On the distribution, create a key group with the public key, and add that key group as a trusted key group on the cache behavior whose path pattern matches /videos/. Serve the app and the content from the same parent domain so the browser sends the cookies.
Exercise
Your behavior for /private/* lists a trusted key group, and the bucket policy trusts the distribution through OAC. A user pastes a signed URL that expired yesterday. What status does the user get, and does S3 see the request?
Show answer
CloudFront returns 403 from the edge because the expiry has passed. S3 never sees the request, even if the object is in the edge cache.