How to serve premium/private content on your site?
Tags: aws, python, serverless, cloud
Published: 2020-08-23 03:46:08

A lot of online companies (for example: Netflix, Udemy etc ) distribute contents over internet that is accessible only to the members of the site or who have subscribed or paid a premium. Today in this post we see how you can achieve this for your website using Amazon Web Services. We will see how you can securely serve private content to your users from AWS S3 bucket using S3 Presigned URLs
### What are Presigned URLs?
A **Presigned URL** is a **URL** that provides limited permission and time to make a request. Anyone who receives the presigned URL can then access the object. For example, if you have a file in your bucket and both the bucket and the object are private, you can share the file with others by generating a presigned URL. 

#### Some important points on Presigned URLs

- The creator of Presigned URL should have access to object for URL to work, otherwise URL wont work.
- You can create a presigned URL that's are not usable or doesn’t work. 
- It doesn’t cost anything to create Presigned URLs.
- You can set expiration time on the URLs 
- If you created a presigned URL using a temporary token, then the URL expires when the token expires, even if the URL was created with a later expiration time
- You can revoke the URL by removing the permissions to access the object from the user created the URL.

### How to create Presigned URL?

When you create a presigned URL for your object, you must provide your security credentials, specify a bucket name, an object key, specify method and expiration time.

In Python, using Boto3, you can use *generate_presigned_url* method to generate the URL
```
response = s3_client.generate_presigned_url('get_object',
            Params={'Bucket': bucket_name,
            'Key': object_name},
            ExpiresIn=expiration)
```
The *response* object will contain the URL which will look similar to this

```
https://somebucketname-rep.s3.amazonaws.com/someFileName.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIAQS3IOUWUZF7YSXGA%2F20200821%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20200821T051228Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Security-Token=FwoGZXIvYXdzEH8aDCfJDxO0y6xQxYmdGCK2AXe71W%2FgZEg%2FSnSWC%2Fw%2FaJHeZ20M7OI7AqMEum5c98Chl6pSNPwE5Awsc3ySwokDF6L8a9wP0ceXWAmxT3WXLSoFeNHDbbEHfUKWnvGL8yFzAxdmf%2Fmi%2B5Tnl62td8Nad%2F0Ct1Sx11Mip1h2qdYxw80OX5bCTq7cAHHjpmupvaDt%2BZ3qVyIA9WZmeS63dCPOlieE9IiBZf%2FjxF4Mcs5w4ZIHtZL%2F3LvqMXAy3XfzCgnlYVZeCNczKLuv%2FfkFMi0mStwkzyO%2BfMIxWJ82GJmyNi7LZuY5r0Hx0mE%2BxLnre8jp9%2FACoV%2FM92GnsR0%3D&X-Amz-Signature=17046b630ad4dede85af1cd57204bba8adc462a1825a35d93e81b656c683ad75
```
You can use this URL in the browser and access the object! Simple.. isn't it?

### Lets see it in Action

We are going to implement this on top of previous two posts, [in the first post](https://blog.rajanpanchal.net/aws-kms-use-case-with-serverless-application-model-sam-an-end-to-end-solution-ckdfenqag00lsqqs1csp05vhj), we implemented custom identity broker(signup/login), using AWS KMS to encrypt decryt password. In [second post](https://blog.rajanpanchal.net/how-to-give-access-to-aws-resources-without-creating-100s-of-iam-users-ckds91qj100pf97s1gc3v8vwb), we used AWS STS to AssumeRole to read bucket files names and now we will extend that to use presigned url. Download code for second post from github.com/rajanpanchal/aws-kms-sts and modify it.
Here is how overall process looks like
![free cloud storage on s3, presigned URL diagram](https://s3.amazonaws.com/blog-images-rajanpanchal.net/presignedUrl/presignedurl_diagram.png)

Open file showFiles.py from the Lamdba folder and lets add function to generate presigned URL. Call this function from *getFilesList* function.

```PYTHON
def getSignedUrl(key,s3_client):
    KeyUrl = {}
    
    response = s3_client.generate_presigned_url('get_object',
                        Params={'Bucket': os.environ['filesBucket'],
                        'Key': key},
                        ExpiresIn=3600)
    KeyUrl[key] = response
    return KeyUrl
    

# Returns list of files from bucket using STS    
def getFilesList():
    sts_client = boto3.client('sts')

    # Call the assume_role method of the STSConnection object and pass the role
    # ARN and a role session name.
    assumed_role_object=sts_client.assume_role(
        RoleArn=os.environ['s3role'],
        RoleSessionName="AssumeRoleSession1"
    )
    
    # From the response that contains the assumed role, get the temporary 
    # credentials that can be used to make subsequent API calls
    credentials=assumed_role_object['Credentials']
    
    # Use the temporary credentials that AssumeRole returns to make a 
    # connection to Amazon S3  
    s3_resource=boto3.resource(
        's3',
        aws_access_key_id=credentials['AccessKeyId'],
        aws_secret_access_key=credentials['SecretAccessKey'],
        aws_session_token=credentials['SessionToken'],
    )
    s3_client = boto3.client('s3',aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken'])
    bucket = s3_resource.Bucket(os.environ['filesBucket'])
    files=[]
    for obj in bucket.objects.all():
        files.append(getSignedUrl(obj.key,s3_client))
    return files
```
We are using the temporary credentials obtained from *AssumeRole* to generate Presigned URL in *getSignedUrl* function. The *getFilesList* functions returns list of file names and presigned URL.

Now, modify showFiles.html, to iterate over response and create links for files

```HTML
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" integrity="sha512-8bHTC73gkZ7rZ7vpqUQThUDhqcNFyYi2xgDgPDHc+GXVGHXq+xPjynxIopALmOPqzo9JZj0k6OqqewdGO3EsrQ==" crossorigin="anonymous" />
<script
  src="https://code.jquery.com/jquery-3.1.1.min.js"
  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
  crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
</head>
<body>

<div class="ui raised very text container">
<h1 class="ui header">File Access System</h1>
<i class="folder open icon"></i></i><div class="ui label">Files</div>
<div id="files" >Loading..</div>
</div>
</body>
<script>

fetch("	https://g4m3zpzp95.execute-api.us-east-2.amazonaws.com/Prod/showFiles/", {
  credentials: 'include'
})
  .then(response => response.text())
  .then((body) => {
    var files="";
	
	var obj = JSON.parse(body)
	for (i = 0; i < obj.length; i++) {
			var o = obj[i]
			
			for(x in o){
				files =  files+ "<i class='file alternate outline icon'><a href='"+o[x]+"' target='_blank'>&nbsp;&nbsp;"+x+"</a>"
			}
	}
    document.getElementById("files").innerHTML= files
  })
  .catch(function(error) {
    console.log(error); 
  });

</script>
</html>

```
Now do SAM build and Deploy.
![Free cloud storage Presigned URL](https://s3.amazonaws.com/blog-images-rajanpanchal.net/presignedUrl/presignedUrlStack.PNG)

Modify login.html, signup.html and showFiles.html to update the api urls from cloudformation outputs.
Upload these files to the bucket *stsexamplebucket* or the bucket you created. Keep these files Public

You can find the code here:  
https://github.com/rajanpanchal/aws-kms-sts-presigned-url

### Testing
![private content serve using Presigned URL](https://s3.amazonaws.com/blog-images-rajanpanchal.net/presignedUrl/testingVideo.gif)

Let me know if you have any questions or comments!