简体   繁体   中英

How to create an s3 download link which will expire only after 6 days

I want to generate an s3 link to download a file, the link should be live for at least 6 days. I have tried with options InstanceProfileCredentialsProvider(false)(Which worked only for 24 hours), ProfileCredentialsProvider(doesn't even create a link ), Access Key

Access key of IAM user worked, but this user key will expire after some days so every time I have to change the same in the code and also I think it is not a good practice to expose the key in the code.

Is there any other way I can generate an s3 download link which will expire only after 6 days.

Below is the code snippet:-

AmazonS3 s3Client  = AmazonS3ClientBuilder.standard().withCredentials(new InstanceProfileCredentialsProvider(false))
                    .build();
java.util.Date expiration = new java.util.Date();
long milliSeconds = expiration.getTime();
milliSeconds += 1000 * 60 * 60 * 24 * 7; // Add 7 days.
expiration.setTime(milliSeconds);
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest("s3bucket",
                    "fileLocationpath");
generatePresignedUrlRequest.setMethod(HttpMethod.GET);
generatePresignedUrlRequest.setExpiration(expiration);
link =  s3Client.generatePresignedUrl(generatePresignedUrlRequest);

The general idea of the way that you implement your solution is the proper way as suggested by AWS.

About the user key that expires after 80 days, as the user keys do not expire automatically and they are valid until you deactivate them, i imagine that this is a process that you set up in order to rotate your credentials for security reasons. That's a very good practice indeed. In order to avoid hard code these credentials in the code, something that is a bad practice, you can just set up your credentials as an environment variable or store them in the AWS credentials file in your instance. By doing this you can then easily rotate them through your deployment pipeline.

You can make the ./aws/credentials configuration through user data, when you start an ec2 instance. You will run "aws configure" and then pass your aws credentials to set them up in your ec2 instance. Ideally you will have a CI/CD pipeline which will automate the whole process instead for doing this manually.

Please see below recommended best practices by AWS:

Presigned URL for s3 buckets - Recommended ways

https://aws.amazon.com/premiumsupport/knowledge-center/presigned-url-s3-bucket-expiration/

AWS access keys best practices

https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html

Configuration and Credential File Settings

https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html

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