简体   繁体   中英

Cloudfront signed URL with python boto3 getting a ccess denied

I have done below steps:

  1. Created S3 bucket with public access blocked.
  2. Created cloudfront distribution pointing to the S3.
  3. Specified to use OAI and verified that bucket policy is updated to allow OAI.
  4. Restrict Viewer Access = Yes
  5. Trusted Authorization type = Truster signer, Truster signers = Self
  6. Went to security credentials on root user and created a cloudfront key.
  7. Downloaded the public key to local system and added to the python code.
  8. Got the Access Key ID from the credentials and added to the python code.

Python code: (Same as from https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html )

import datetime

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 botocore.signers import CloudFrontSigner


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()
        )
    return private_key.sign(message, padding.PKCS1v15(), hashes.SHA1())

key_id = 'AKIAIOSFODNN7EXAMPLE'
url = 'http://d2949o5mkkp72v.cloudfront.net/hello.txt'
expire_date = datetime.datetime(2022, 10, 11)

cloudfront_signer = CloudFrontSigner(key_id, rsa_signer)

# Create a signed url that will be valid until the specific expiry date
# provided using a canned policy.
signed_url = cloudfront_signer.generate_presigned_url(
    url, date_less_than=expire_date)
print(signed_url)

I tried to base64 decode the signature part, but it gives error like Invalid character in input stream. Other question i have is, can i create multiple signed urls for the same object? When we did not have the Restrict Viewer Access = Yes, the signed URL was working. I Know it does not matter, cos signed url should be working with restricted access on.

I also tried creating a signed url using Perl, with the code given by AWS, but even that is not working. Same access denied.

https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CreateURLPerl.html

Just like many things in life, this was a small error.

I missed to add the trailing / in the URL that was the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM