Generate a Presigned Object URL Using the AWS Java SDK

An Amazon S3 bucket is a public cloud storage resource available in Amazon Web Services' (AWS) Simple Storage Service (S3), an object storage offering. Amazon S3 buckets, which are similar to file folders, store objects, which consist of data and its descriptive metadata

What is a Presigned URL?

A user who does not have AWS credentials or permission to access an S3 object can be granted temporary access by using a Presigned URL.

A Presigned URL is generated by an unauthorized AWS user who has access to the object. The generated URL is then given to the unauthorized user.

The Backend user code generate Presigned URL using the AWS credentials and returns the front end framework like AngularJs to upload the files to the s3 bucket.

This URL can be generated by the SDK of different languages. Here we are using AWS Java SDK to generate Presigned URL for upload and download the files that are present in the S3 Bucket.

1).Create a maven project with quickstart archetype

Please refer this article to create a maven project

then aad this dependency in pom.xml file

We needed a maven dependency

 
<dependency>
    <groupid>com.amazonaws</groupid>
    <artifactid>aws-java-sdk-s3</artifactid>
    <version>1.11.795</version>
</dependency>


2). Creating a Java class to generate Presigned URL.

 

import com.amazonaws.AmazonServiceException;
import com.amazonaws.HttpMethod;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;

import java.io.IOException;
import java.net.URL;

public class GeneratePresignedUrlForUpload {

    public static void main(String[] args) throws IOException {
        Regions bucketRegion = Regions.AP_SOUTH_1;// region where your bucket is located 
        String bucketName = "test-bucket"; //bucketName
        String objectKey = "doc/hello.pdf"; //file locaion in s3 Bucket

        try {
            AmazonS3 s3Client =  AmazonS3ClientBuilder.standard().withCredentials(new                                             DefaultAWSCredentialsProviderChain()).withRegion(bucketRegion).build(); // need to follow tutorial menioned in above link

            // Set the presigned URL to expire after one hour.
            java.util.Date expiration = new java.util.Date();
            long expTimeMillis = expiration.getTime();
            expTimeMillis += 1000 * 60 * 5;//its for 5 minutes user need to upload file within 5 minues.
            expiration.setTime(expTimeMillis);

            // Generate the presigned URL.
            System.out.println("Generating pre-signed URL.");
            GeneratePresignedUrlRequest generatePresignedUrlRequest =
                    new GeneratePresignedUrlRequest(bucketName, objectKey)
                            .withMethod(HttpMethod.GET)
                            .withExpiration(expiration);
            URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);

            System.out.println("Pre-Signed URL: " + url.toString());
        } catch (AmazonServiceException e) {
            // The call was transmitted successfully, but Amazon S3 couldn't process 
            // it, so it returned an error response.
            e.printStackTrace();
        } catch (SdkClientException e) {
            // Amazon S3 couldn't be contacted for a response, or the client
            // couldn't parse the response from Amazon S3.
            e.printStackTrace();
        }
    }
}


Suppose your file is located in s3 and you want to give access to the user to file for a certain time. Here we generated Presigned Url for file download.

The code is the same as generating Presigned URL for upload, the addition of this code

 
ResponseHeaderOverrides overrides = new ResponseHeaderOverrides();
overrides.setContentDisposition("attachment; filename=\"hello.pdf\"");
req.setResponseHeaders(overrides);


3). Code for Presigned URL download file

 

import com.amazonaws.AmazonServiceException;
import com.amazonaws.HttpMethod;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;

import java.io.IOException;
import java.net.URL;

public class GeneratePresignedURLForUpload {
    public static void main(String[] args) throws IOException {
        Regions bucketRegion = Regions.AP_SOUTH_1;// region where your bucket is located 
        String bucketName = "test-bucket"; //bucketName
        String objectKey = "doc/hello.pdf"; //file locaion in s3 Bucket

        try {
            AmazonS3 s3Client =  AmazonS3ClientBuilder.standard().withCredentials(new                            DefaultAWSCredentialsProviderChain()).withRegion(bucketRegion).build(); 


           // Set the presigned URL to expire after 5 mintues.
            java.util.Date expiration = new java.util.Date();
            long expTimeMillis = expiration.getTime();
            expTimeMillis += 1000 * 60 * 5;
            expiration.setTime(expTimeMillis);



             System.out.println("Generating pre-signed URL.");
             GeneratePresignedUrlRequest generatePresignedUrlRequest =
                    new GeneratePresignedUrlRequest(bucketName, objectKey)
                            .withMethod(HttpMethod.GET)
                            .withExpiration(expiration);

			ResponseHeaderOverrides overrides = new ResponseHeaderOverrides();
			overrides.setContentDisposition("attachment; filename=\"report.html\"");
			req.setResponseHeaders(overrides);

            URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);

            System.out.println("Pre-Signed URL For File Download is : " + url.toString());
      } catch (AmazonServiceException e) {
            // The call was transmitted successfully, but Amazon S3 couldn't process 
            // it, so it returned an error response.
            e.printStackTrace();
        } catch (SdkClientException e) {
            // Amazon S3 couldn't be contacted for a response, or the client
            // couldn't parse the response from Amazon S3.
            e.printStackTrace();
        }
    }
}            


In this article, We have seen how to Generate a presigned Object URL for upload/download files to the S3 bucket using the AWS SDK. For full source code please check our article GitHub Repository.