'Cloudfront signed URL with python boto3 getting a ccess denied
I have done below steps:
- Created S3 bucket with public access blocked.
- Created cloudfront distribution pointing to the S3.
- Specified to use OAI and verified that bucket policy is updated to allow OAI.
- Restrict Viewer Access = Yes
- Trusted Authorization type = Truster signer, Truster signers = Self
- Went to security credentials on root user and created a cloudfront key.
- Downloaded the public key to local system and added to the python code.
- 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
Solution 1:[1]
Just like many things in life, this was a small error.
I missed to add the trailing / in the URL that was the problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | manu muraleedharan |
