繁体   English   中英

过期时间更长的 S3 链接

[英]S3 link with longer expiration

我正在使用客户端的 java sdk 生成预签名链接。 我们有新的要求,允许链接保持活动状态至少 30 天。 当我将到期时间设置得更长时,我收到以下错误:

由 SigV4 算法预签名的请求最长有效期为 7 天

我需要确定一种解决方法,因为客户端无法接受对链接的更新(例如,如果我只是每周自动生成更新)。 有没有办法解决这个问题? 我可以通过一组给定的只读凭据吗?

有关日期限制的说明,请参阅此详细答案

为客户端生成只读凭据将无法正常工作,因为客户端必须使用这些凭据来创建自己的预签名 URL(与您现在所做的没有什么不同——它仍然会在最多 7 天后过期)或使用 AWS 开发工具包直接下载文件,无需预先签名的 URL。

使用 SigV4 并拥有超过 7 天的恒定链接可以通过中间层(如 REST 端点)完成,其 URL 不会更改并在请求时提供文件。

不幸的是,使用 S3 预签名 url 不可能超过 7 天。

一种可能的解决方案是使用 CloudFront 签名的 urls ,这些对 url 的有效时长没有“限制”。 S3 存储桶仍将保持私有。

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

Java 示例:

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

import logging
import boto3
from botocore.exceptions import ClientError
from botocore.client import Config

# python > 3 should be installed
# pip install boto3
# s3v4
# (Default) Signature Version 4
# v4 algorithm starts with X-Amz-Algorithm
#
# s3
# (Deprecated) Signature Version 2,  this only works in some regions new regions not supported
# if you have to generate signed url that has > 7 days expiry then use version 2 if your region supports it. below code illustration of this

s3_signature ={
    'v4':'s3v4',
    'v2':'s3'
}

def create_presigned_url(bucket_name, bucket_key, expiration=3600):
    """Generate a presigned URL to share an S3 object

    :param bucket_name: string
    :param bucket_key: string
    :param expiration: Time in seconds for the presigned URL to remain valid
    :return: Presigned URL as string. If error, returns None.
    """

    # Generate a presigned URL for the S3 object
    s3_client = boto3.client('s3',
                             aws_access_key_id='your_access_key_here',
                             aws_secret_access_key='your_secret_key_here',
                             config=Config(signature_version=s3_signature['v2']),
                             region_name='us-east-1'
                             )
    try:
        response = s3_client.generate_presigned_url('get_object',
                                                    Params={'Bucket': bucket_name,
                                                            'Key': bucket_key},
                                                    ExpiresIn=expiration)
    except ClientError as e:
        logging.error(e)
        return None

    # The response contains the presigned URL
    return response

weeks = 8

seven_days_as_seconds = 604800

signed_url = create_presigned_url('your_bucket_here', 'your_key/file_name.xls', (seven_days_as_seconds*weeks))

print(signed_url)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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