This post assumes that you already set your S3 bucket and CloudFront distribution to serve private contents. The process is well documented in the Amazon CloudFront Developer Guide. You can follow it if you did not set them up yet.
Choosing signed URLs over signed cookies can make things easier, or more suitable for your application. However, signed cookies are reasonable when the following situation:
“CloudFront signed cookies allow you to control who can access your content when you don’t want to change your current URLs or when you want to provide access to multiple restricted files, for example, all of the files in the subscribers’ area of a website.”
To create signed cookies, you need to set three cookies with the value; CloudFront key pair ID, CloudFront policy string, and CloudFront signature string.
First, you need to coin the policy statement to create signed cookies. You can use either canned policy or custom policy. I chose to use the custom policy because:
- I can use a policy statement for multiple objects.
- I can specify the date or time that the user can access the objects.
There is more information about choosing between them on the Amazon CloudFront Developer Guide.
Following is the code creating the custom policy and base64 encoding it to make the policy string.
Your CNAME is the alternative domain name that you set for the CloudFront distribution, for example, video.mydomain.com. (This setting is requisite if you want to use your own domain for the contents, or set cookies and refer the contents from your own domain. Say, if things not work, USE CNAME.)
Next step is creating a signature string. The signature string is a hashed, signed, and base64-encoded version of the JSON.
Finally, you need to set three cookies with the values you created.
‘res’ is the response object from the Express. If you use HTTP instead of Express, then you can set cookies in the way of the comment, using res.writeHead().