TEQ

Tech Docs

Make a temporary public URL/link for a private file in s3 with an expiry

When I was working in an e-commerce project where users buy ebooks, videos, and audio files, I came across this solution. The requirement was to give a download URL/link which should expire after a few days for users who purchased the item.

In case you have a similar requirement you can refer to this, In case you need a modified version of this, reach me out.

What we are using

  • Pre-Signed URLs for Amazon S3 Buckets
  • Python boto3 for scripting
Pre-Signed URL

Generating a pre-signed URL for an Amazon S3 object will allow anyone who receives the pre-signed URL to retrieve the S3 object with an HTTP GET request.

Python boto

Boto is the Amazon Web Services (AWS) SDK for Python. It enables Python developers to create, configure, and manage AWS services, such as EC2 and S3. Boto provides an easy to use, object-oriented API, as well as low-level access to AWS services.

Let’s get started

For this we need to have python3, pip, and boto installed and aws credentials configured in the system.

If everything above it set create a file and add the below code. Edit your bucket name and required expiry for the URL.

import boto3
import sys
s3 = boto3.client('s3')
url = s3.generate_presigned_url(
ClientMethod='get_object',
Params={
'Bucket': 'BUCKET_NAME',
'Key': sys.argv[1],
'ResponseContentDisposition': 'attachment'
},
ExpiresIn=604800
)
print(url)

I have kept the Key to be passed as an argument, which means if my script name is presigned_url.py, issuing ‘presigned_url.py picture1.jpg‘ will create a pre-signed URL for picture1.jpg.

Edit ‘ExpiresIn’ parameter with respect to your requirement. the maximum expiry we can give is 604800 seconds, which is 7 days.

‘ResponseContentDisposition’ parameter is set to ‘attachment’ so that the file will be directly downloaded instead of opening it in the browser.

You can call the script in any application like PHP along with the Key as argument, so that it will create a pre-signed URL for the object.