{{announcement.body}}
{{announcement.title}}

How to Serve Premium/Private Content on Your Site?

DZone 's Guide to

How to Serve Premium/Private Content on Your Site?

Learn how to use AWS S3 Presigned URL to serve private content to the users.

· Cloud Zone ·
Free Resource

A lot of online companies distribute contents over the 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 the presigned URL should have access to the object for URL to work, otherwise URL won't 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 an 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 a 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.

Python
 




x


1
response = s3_client.generate_presigned_url('get_object',
2
            Params={'Bucket': bucket_name,
3
            'Key': object_name},
4
            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? 

Let's See It in Action

We are going to implement this on top of previous two posts, in the first post, we implemented custom identity broker (signup/login), using AWS KMS to encrypt decrypt password. In the second post, we used AWS STS to AssumeRole to read bucket files names and now we will extend that to use presigned URL. Download code for the second post from  https://github.com/rajanpanchal/aws-kms-sts and modify it. Here is how the overall process looks like:

Private content to presigned URL

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

Python
 




x
42


 
1
def getSignedUrl(key,s3_client):
2
    KeyUrl = {}
3
 
          
4
    response = s3_client.generate_presigned_url('get_object',
5
                        Params={'Bucket': os.environ['filesBucket'],
6
                        'Key': key},
7
                        ExpiresIn=3600)
8
    KeyUrl[key] = response
9
    return KeyUrl
10
 
          
11
 
          
12
# Returns list of files from bucket using STS    
13
def getFilesList():
14
    sts_client = boto3.client('sts')
15
 
          
16
    # Call the assume_role method of the STSConnection object and pass the role
17
    # ARN and a role session name.
18
    assumed_role_object=sts_client.assume_role(
19
        RoleArn=os.environ['s3role'],
20
        RoleSessionName="AssumeRoleSession1"
21
    )
22
 
          
23
    # From the response that contains the assumed role, get the temporary 
24
    # credentials that can be used to make subsequent API calls
25
    credentials=assumed_role_object['Credentials']
26
 
          
27
    # Use the temporary credentials that AssumeRole returns to make a 
28
    # connection to Amazon S3  
29
    s3_resource=boto3.resource(
30
        's3',
31
        aws_access_key_id=credentials['AccessKeyId'],
32
        aws_secret_access_key=credentials['SecretAccessKey'],
33
        aws_session_token=credentials['SessionToken'],
34
    )
35
    s3_client = boto3.client('s3',aws_access_key_id=credentials['AccessKeyId'],
36
aws_secret_access_key=credentials['SecretAccessKey'],
37
aws_session_token=credentials['SessionToken'])
38
    bucket = s3_resource.Bucket(os.environ['filesBucket'])
39
    files=[]
40
    for obj in bucket.objects.all():
41
        files.append(getSignedUrl(obj.key,s3_client))
42
    return files



We are using the temporary credentials obtained from AssumeRole to generate a 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
 




xxxxxxxxxx
1
43


1
<html>
2
<head>
3
<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" />
4
<script
5
  src="https://code.jquery.com/jquery-3.1.1.min.js"
6
  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
7
  crossorigin="anonymous"></script>
8
 
          
9
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
10
</head>
11
<body>
12
 
          
13
<div class="ui raised very text container">
14
<h1 class="ui header">File Access System</h1>
15
<i class="folder open icon"></i></i><div class="ui label">Files</div>
16
<div id="files" >Loading..</div>
17
</div>
18
</body>
19
<script>
20
 
          
21
fetch("    https://g4m3zpzp95.execute-api.us-east-2.amazonaws.com/Prod/showFiles/", {
22
  credentials: 'include'
23
})
24
  .then(response => response.text())
25
  .then((body) => {
26
    var files="";
27
 
          
28
    var obj = JSON.parse(body)
29
    for (i = 0; i < obj.length; i++) {
30
            var o = obj[i]
31
 
          
32
            for(x in o){
33
                files =  files+ "<i class='file alternate outline icon'><a href='"+o[x]+"' target='_blank'>&nbsp;&nbsp;"+x+"</a>"
34
            }
35
    }
36
    document.getElementById("files").innerHTML= files
37
  })
38
  .catch(function(error) {
39
    console.log(error); 
40
  });
41
 
          
42
</script>
43
</html>


Do SAM build and Deploy. 

SAM Build

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

Testing

Let me know if you have any questions or comments!

Topics:
aws, cloud, how-to guides, presigned url, python, s3 bucket, serverless

Published at DZone with permission of Rajan Panchal . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}