Access Private Objects Using Presigned URLs
For private objects stored in OSS, use a presigned URL to grant temporary access without modifying bucket or object permissions. The following steps demonstrate how to generate and use a presigned URL with the AWS SDK for Java (v2).
Steps:
-
Initialise S3Presigner
Create an
S3Presigner
instance with the required credentials, region, and OSS endpoint:public S3Presigner createS3Presigner() {
AwsBasicCredentials awsCredentials = AwsBasicCredentials.create("accessKeyId", "secretAccessKey");
return S3Presigner.builder()
.serviceConfiguration(S3Configuration.builder().pathStyleAccessEnabled(true).build())
.region(Region.of("default"))
.endpointOverride(URI.create("Access Endpoint"))
.credentialsProvider(StaticCredentialsProvider.create(awsCredentials))
.build();
} -
Generate a Presigned URL
Generate a presigned URL valid for a specific duration (e.g., 10 minutes):
public String createPresignedGetUrl(String bucketName, String keyName) {
try (S3Presigner presigner = S3Presigner.create()) {
GetObjectRequest objectRequest = GetObjectRequest.builder()
.bucket(bucketName)
.key(keyName)
.build();
GetObjectPresignRequest presignRequest = GetObjectPresignRequest.builder()
.signatureDuration(Duration.ofMinutes(10))
.getObjectRequest(objectRequest)
.build();
PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(presignRequest);
return presignedRequest.url().toExternalForm();
}
} -
Access the Object
Use a standard HTTP client to access the object with the presigned URL:
public byte[] useHttpUrlConnectionToGet(String presignedUrlString) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
URL presignedUrl = new URL(presignedUrlString);
HttpURLConnection connection = (HttpURLConnection) presignedUrl.openConnection();
connection.setRequestMethod("GET");
try (InputStream content = connection.getInputStream()) {
IoUtils.copy(content, byteArrayOutputStream);
}
} catch (S3Exception | IOException e) {
logger.error(e.getMessage(), e);
}
return byteArrayOutputStream.toByteArray();
}