AWS S3预签名URL与自定义策略结合使用可以实现更精细的访问控制。下面是一个使用Python语言编写的示例代码,演示了如何生成具有自定义策略的S3预签名URL:
import boto3
from botocore.exceptions import ClientError
import datetime
def generate_presigned_url(bucket_name, object_name, expiration=3600, custom_policy=None):
"""Generate a presigned URL to share an S3 object
:param bucket_name: string
:param object_name: string
:param expiration: Time in seconds for the presigned URL to remain valid
:param custom_policy: Custom policy string as JSON format
:return: Presigned URL as string. If error, returns None.
"""
# Generate a presigned URL for the S3 object
s3_client = boto3.client('s3')
try:
params = {
'Bucket': bucket_name,
'Key': object_name
}
if custom_policy:
params['Policy'] = custom_policy
url = s3_client.generate_presigned_url(
'get_object',
Params=params,
ExpiresIn=expiration
)
return url
except ClientError as e:
print(e)
return None
# 示例用法
bucket = 'your-bucket-name'
object_key = 'your-object-key'
# 创建自定义策略
policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": f"arn:aws:s3:::{bucket}/{object_key}",
"Condition": {
"IpAddress": {
"aws:SourceIp": "192.168.0.1/24"
}
}
}
]
}
# 将策略转换为JSON字符串
import json
policy_json = json.dumps(policy)
# 生成预签名URL
url = generate_presigned_url(bucket, object_key, expiration=3600, custom_policy=policy_json)
print(url)
上述代码中的generate_presigned_url函数用于生成带有自定义策略的S3预签名URL。你可以根据自己的需求修改策略中的条件和资源等信息。
注意,预签名URL的有效期可以自行设置,默认为3600秒。此外,代码中使用的策略为示例策略,你需要根据自己的需求自行编写适用的策略。
希望对你有所帮助!