Using a signed cookie to distribute AWS S3 content
This blog is about distributing private S3 bucket content through CloudFront using the signed Cookie. Client applications can either upload or download multiple files from a specific path which is restricted in the signed Cookie.
Why do we need it?
- When there is a requirement to prevent users from accessing content directly on the origin server (for example, Amazon S3 or a private HTTP server)
- When there is a need to prevent users from bypassing the restrictions that you specify in the signed cookies.
- We can apply various kinds of restrictions as follows.
1) Time duration(You can specify the date and time that users can begin to access your content).
2) IP restriction (You can specify the IP address or range of IP addresses of the users who can access your content)
Here are the steps to achieve it.
1. Create RSA keypair using OpenSSL Tool.
2. Create CloudFront Distribution, S3 bucket & key group with Terraform script.
3. Sign a cookie .NET Core code using Private Key & share it with client application.
Step 1: Use the following commands to create RSA keys with OpenSSL CLI.
openssl genrsa -out private_key.pem 2048 openssl rsa -pubout -in private_key.pem -out public_key.pem
Step 2: Download Terraform script from here to create S3 bucket, CloudFront Distribution and Trusted Key Group. It also creates Origine Access Identity in CloudFront and updates S3 bucket policy.
Terraform scrip output will have CloudFront DNS and public key Id. The details are required for generating signed URLs in the next step.
Step 3: To create a signed cookie for a resource in S3 bucket using AmazonCloudFrontCookieSigner
You can find complete code here