logo
Menu

Secure File Uploads to S3 Using AWS Lambda

This simple python script demonstrates how can we generate s3 presigned url using lambda function for secure file upload.

Published Apr 8, 2024

Introduction:

Uploading files securely to an S3 bucket is a common requirement for many applications.I found thta AWS Lambda, coupled with S3 presigned URLs, provides an efficient and secure solution to achieve this. This post will guide you through a simple Lambda function written in Python that generates a presigned URL for general file uploads to an S3 bucket.

Prerequisites:

  • AWS account with Lambda and S3 access.
  • Basic knowledge of AWS services

Step-by-Step Guide:

  1. Create an S3 Bucket:
  • Log in to your AWS Management Console.
  • Navigate to S3 and create a new bucket, e.g., 'file-upload-bucket2023'.
  1. Set Up Lambda Function:
Go to AWS Lambda service in the console.
  • Click on 'Create function,' choose 'Author from scratch,' and give your function a name.
  • Select Python as the runtime.
  • In the Function code section, paste the provided Python code.
import boto3
from botocore.exceptions import NoCredentialsError
from datetime import datetime
def lambda_handler(event, context):
current_time = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
bucket_name = 'file-upload-bucket2023'
object_key = f'object_key-{current_time}.zip'
try:
presigned_url = generate_presigned_url(bucket_name, object_key)
if presigned_url:
print("The url succefully generated")
return presigned_url
else:
return {
'statusCode': 500,
'body': "Failed to generate pre-signed URL."
}
except Exception as e:
return {
'statusCode': 500,
'body': f"An error occurred: {str(e)}"
}
def generate_presigned_url(bucket_name, object_name,
expiration_time=3600):
s3_client = boto3.client('s3')
try:
response = s3_client.generate_presigned_url(
'put_object',
Params={
'Bucket': bucket_name,
'Key': object_name,
'ContentType': "application/x-zip-compressed",
},
ExpiresIn=expiration_time,
)
except NoCredentialsError:
print("Credentials not available")
return None
return response
3. Configure Lambda Trigger:
In the Lambda Designer, click 'Add trigger.'
Choose an appropriate trigger for your use case. For example, you can use Function URL, API Gateway or an S3 event to invoke the Lambda function.
4. Deploy the Lambda Function:
Click 'Deploy' to save your Lambda function.
5. Test the Lambda Function:
In the Lambda Designer, click 'Test' to manually invoke the Lambda function.
Check the CloudWatch logs for the generated presigned URL.
7. Implement Frontend (Optional):
Build a frontend application where users can select files and use the generated URL to upload them to the S3 bucket.
**Conclusion:**
AWS Lambda, combined with S3 presigned URLs, simplifies the process of securely allowing users to upload files to your S3 bucket. This serverless architecture ensures that only authorized users can upload files, enhancing the security of your application. Feel free to customize the code and integrate additional features based on your specific requirements.
Since I am junior on AWS, if I miss anything, let me know.
 

Comments