Serving Private Files From S3 Bucket – AWS in Java

If you are building any kind of application, you will most likely need to store and display images or other types of files. This tutorial will quickly show you how to access private images on your S3 Bucket.

By default, if you try to access an image via URL, that is not publicly available you will see something like this:

<Message>Access Denied</Message>

In order to serve your image to the front end without having to make it public you will need to use your IAM user credentials (Access Key Id and Secret Access Key) to generate a temporary URL and pass it to the front end.

In Java, to do this, you could write a simple method like so:

public static URL generatePresignedUrlRequest(String image){
        BasicAWSCredentials awsCreds = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
        AmazonS3 s3client = new AmazonS3Client(awsCreds);
        java.util.Date expiration = new java.util.Date();
        long msec = expiration.getTime();
        msec += 1000 * 60 * 60; // 1 hour.
        GeneratePresignedUrlRequest generatePresignedUrlRequest =
                new GeneratePresignedUrlRequest(BUCKET_NAME, image);
        generatePresignedUrlRequest.setMethod(HttpMethod.GET); // Default.
        URL s = s3client.generatePresignedUrl(generatePresignedUrlRequest);
        return s;

The method takes in the Object Key (aka filename as defined in your bucket), and generates a URL that is valid for a set period of time (in this case 1 hour).
This keeps your images secure and does not give the public access to them without your secret keys!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>