Signed HTTPS URL to S3 using boto

I needed protected downloads for a project using S3 on a HTTPS Django site. There are various ways to solve this problem, but I thought the most obvious was to offload access control to S3. Boto can generate signed download links that are only valid for a limited time. Great.

However, using HTTPS the hostname needs to be changed, and the bucket name has to be in the path, not the hostname. The snippet below does both.

def get_protected_url(self, key, **kwargs):                                                        
    connection = S3Connection(                                                                     
        AWS_ACCESS_KEY_ID,                                                          
        AWS_SECRET_ACCESS_KEY,                                                      
        is_secure=True,                                                                      
        calling_format='boto.s3.connection.OrdinaryCallingFormat',                           
        host='s3.eu-central-1.amazonaws.com',                                        
    )                                                                                        
    # Create a URL valid for 60 seconds.                                                     
    s3_url = connection.generate_url(                                                              
        60,                                                                                  
        'GET',                                                                               
        bucket='',  # Required                                                                          
        key=key,                                                              
    )                                                                                        
    return s3_url
Published on April 10, 2017 at 6:40 p.m. by Nicolas . You can follow the discussion with the comment feed for this post. Feeling generous? Donate!

0 comments

Start a new thread

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.