| 1 |
Generate a signed URL for Amazon CloudFront |
| 2 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 3 |
|
| 4 |
The following example shows how to generate a signed URL for Amazon CloudFront. |
| 5 |
Note that you will need the ``cryptography`` `library <https://cryptography.io/en/latest/>`__ to follow this example:: |
| 6 |
|
| 7 |
import datetime |
| 8 |
|
| 9 |
from cryptography.hazmat.backends import default_backend |
| 10 |
from cryptography.hazmat.primitives import hashes |
| 11 |
from cryptography.hazmat.primitives import serialization |
| 12 |
from cryptography.hazmat.primitives.asymmetric import padding |
| 13 |
from botocore.signers import CloudFrontSigner |
| 14 |
|
| 15 |
|
| 16 |
def rsa_signer(message): |
| 17 |
with open('path/to/key.pem', 'rb') as key_file: |
| 18 |
private_key = serialization.load_pem_private_key( |
| 19 |
key_file.read(), |
| 20 |
password=None, |
| 21 |
backend=default_backend() |
| 22 |
) |
| 23 |
return private_key.sign(message, padding.PKCS1v15(), hashes.SHA1()) |
| 24 |
|
| 25 |
key_id = 'AKIAIOSFODNN7EXAMPLE' |
| 26 |
url = 'http://d2949o5mkkp72v.cloudfront.net/hello.txt' |
| 27 |
expire_date = datetime.datetime(2017, 1, 1) |
| 28 |
|
| 29 |
cloudfront_signer = CloudFrontSigner(key_id, rsa_signer) |
| 30 |
|
| 31 |
# Create a signed url that will be valid until the specific expiry date |
| 32 |
# provided using a canned policy. |
| 33 |
signed_url = cloudfront_signer.generate_presigned_url( |
| 34 |
url, date_less_than=expire_date) |
| 35 |
print(signed_url) |