当使用AWS Cloudfront签名URL访问文件夹时,可能会遇到访问被拒绝的问题。这通常是因为签名URL没有正确配置所致。以下是解决此问题的步骤:
确保您已正确配置Cloudfront。
确保您使用的签名URL中包含了正确的桶名称、文件夹名称和文件名。
例如:
https://[cloudfront域名]/[文件夹名称]/[文件名]?[签名]
以下是示例代码,可用于使用Python生成AWS Cloudfront签名URL:
import datetime
import hashlib
import hmac
import urllib.parse
def sign_cloudfront_url(url, expire_time, key_pair_id, private_key):
# Parse the URL into parts
url_parts = urllib.parse.urlparse(url)
# Get the path and query string
path = url_parts.path
query_string = url_parts.query
# Set the time that the URL will expire
expires = int(datetime.datetime.now().timestamp()) + expire_time
# Create the Cloudfront policy statement
policy = f"{{\"Statement\":[{{\"Resource\":\"{path}\",\"Condition\":{{\"DateLessThan\":{{\"AWS:EpochTime\":{expires}}}}}}}]}}"
# Create the policy signature
policy_signature = hmac.new(bytes(private_key, "utf-8"), bytes(policy, "utf-8"), hashlib.sha1).digest()
# Encode the policy signature in base64
policy_signature_b64 = urllib.parse.quote_plus(policy_signature.encode("base64").decode().strip())
# Create the Cloudfront signed URL
signed_url = f"{url}&Expires={expires}&Signature={policy_signature_b64}&Key-Pair-Id={key_pair_id}"
return signed_url
使用该函数可以生成AWS Cloudfront签名URL并解决访问被拒绝的问题。