LoginSignup
2
2

More than 5 years have passed since last update.

Python3+CloudFront+SignedURL

Last updated at Posted at 2017-06-26

参考

http://boto3.readthedocs.io/en/latest/reference/services/cloudfront.html
https://stackoverflow.com/questions/2573919/creating-signed-urls-for-amazon-cloudfront

version

$ pip3 show boto3
Name: boto3
Version: 1.4.4

$ pip3 show cryptography
Name: cryptography
Version: 1.9

$ pip3 show botocore
Name: botocore
Version: 1.5.65

共通関数

from botocore.signers import CloudFrontSigner
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from datetime import datetime, timedelta
import pytz
def rsa_signer(message):
    with open('path/to/key.pem', 'rb') as key_file:
        private_key = serialization.load_pem_private_key(
            key_file.read(),
            password=None,
            backend=default_backend()
        )
    signer = private_key.signer(padding.PKCS1v15(), hashes.SHA1())
    signer.update(message)
    return signer.finalize()

Signed URLを発行

Expiresパラメータを使う場合

5分有効なSinged URL

def rsa_signer(url):
    expire_date = datetime.now().replace(tzinfo=pytz.timezone('Asia/Tokyo')) + timedelta(minutes=5)
    cloudfront_signer = CloudFrontSigner('APK・・・・・・・・', rsa_signer)
    return cloudfront_signer.generate_presigned_url(
        url,
        date_less_than=expire_date,
    )

Policyパラメータを使う場合

5分有効なSinged URL

import json
def rsa_signer(url):
    expire_date = datetime.now().replace(tzinfo=pytz.timezone('Asia/Tokyo')) + timedelta(minutes=5)
    cloudfront_signer = CloudFrontSigner('APK・・・・・・・・', rsa_signer)
        policy = {
        'Statement': [
            {
                'Resource': url,
                'Condition': {
                    'DateLessThan': {
                        'AWS:EpochTime': int(expire_date.timestamp()),
                    }
                }
            }
        ]
    }
    return cloudfront_signer.generate_presigned_url(
        url,
        policy=json.dumps(policy),
    )

hashes.SHA1()
を、
hashes.SHA256()
に変更したら、AccessDenied・・・。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2