Distribute Content With Signed URLs
This blog is about distributing private S3 bucket content through CloudFront using the signed URLs.
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 signed URLs or 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 the CloudFront URL with .NET Core code using Private Key.
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 URL for a resource in S3 bucket using .NET Core, 1st create a Private key in XML format from .PEM file format.
2nd step: Create a signed URL as follows.
The output of the above step is a signed URL (shown below)that you can distribute to the intended users so that they can download the file specified in the URL. The URL consists of 3 query string parameters 1) Expires: It’s a timestamp after which the URL will be invalid. 2)Signature: It is used by CloudFront to validate whether the URL tampers or not. 3) Key-Pair-Id: It is id of the public key uploaded in the CloudFront.
https://dfd8w3fi9tet3.cloudfront.net/main.tf?Expires=1647773597&Signature=btFALlmJWv3O8TK3obQOAfl6GhdmiHpLovHj4HdxvKjlQ9-UOJis9ObfcyrG8bg1nk6mvqdIGZm6-ylmv-QrSU60CkSrNWv0686zvuzRgVmdQqknm1Pn41XRZ-PtfoaKsih4T4WfjT8noD94UmawjeggszoDfmveNP1shJ5x7SKgvIjzN~ZlMUMxgs-9TZzrkj9l1PZzXqWD5DEbe7~lpv594MyT4m30DzvUGX2C2f2LqRwVDwo4YiF2j4BJrzj4cBofbeviAjRG5pqnebiGfSFsWDoe6sCEtSS-a0zfpEWoy0idGazfn1EdWEchq-umwPFhCxTnyy~S3trfg5raCg__&Key-Pair-Id=K2WWZKWQ3LKMM8
You can download complete source code from here.