Creating PreSigned URL for AWS S3 using Apex - Salesforce
To access or download private objects stored in Amazon S3 we require to create Pre Signed URLs. This post will help you understand how to create it using Apex.
For JavaScript Code click -
For JavaScript Code click -
Download from Amazon S3 using JavaScript and Visualforce
Use to below code which takes in the filename and generates the PreSigned URL for S3 which can be accessed for the limited time span. This time span can be modified as well.
Apex Code below:
global class AwsUtility{
public static string getSignedURL(string file) {
String filename = EncodingUtil.urlEncode(file, 'UTF-8');
String BucketName=YOUR Bucket Name ;
String AccessKey= YOUR S3 Access Key;
String SecretKey=YOUR S3 Secret Key;
Datetime now = DateTime.now();
Datetime expireson = now.AddSeconds(60); // Lifespan of the link
Long Lexpires = expireson.getTime()/1000;
String stringtosign = 'GET\n\n\n'+Lexpires+'\n/'+BucketName+'/'+filename;
System.debug('redirectToS3Key stringstosign: ' + stringtosign);
String signingKey = EncodingUtil.base64Encode(Blob.valueOf(SecretKey));
Blob mac = Crypto.generateMac('HMacSHA1', blob.valueof(stringtosign),blob.valueof(SecretKey));
String signed= EncodingUtil.base64Encode(mac);
String codedsigned = EncodingUtil.urlEncode(signed,'UTF-8');
String url = 'http://'+BucketName+'.s3.amazonaws.com/'+filename+'?AWSAccessKeyId='+AccessKey+
'&Expires='+Lexpires+'&Signature='+signed;
return url;
}
}
Feel free to comment !
global class AwsUtility{
public static string getSignedURL(string file) {
String filename = EncodingUtil.urlEncode(file, 'UTF-8');
String BucketName=YOUR Bucket Name ;
String AccessKey= YOUR S3 Access Key;
String SecretKey=YOUR S3 Secret Key;
Datetime now = DateTime.now();
Datetime expireson = now.AddSeconds(60); // Lifespan of the link
Long Lexpires = expireson.getTime()/1000;
String stringtosign = 'GET\n\n\n'+Lexpires+'\n/'+BucketName+'/'+filename;
System.debug('redirectToS3Key stringstosign: ' + stringtosign);
String signingKey = EncodingUtil.base64Encode(Blob.valueOf(SecretKey));
Blob mac = Crypto.generateMac('HMacSHA1', blob.valueof(stringtosign),blob.valueof(SecretKey));
String signed= EncodingUtil.base64Encode(mac);
String codedsigned = EncodingUtil.urlEncode(signed,'UTF-8');
String url = 'http://'+BucketName+'.s3.amazonaws.com/'+filename+'?AWSAccessKeyId='+AccessKey+
'&Expires='+Lexpires+'&Signature='+signed;
return url;
}
}
Feel free to comment !
Thank you! it Works like a charm!
ReplyDeleteCan you explain how to get presigned URL from S3 using the above URL?
ReplyDeleteMainly, what is the request and response API for AWS to get presigned URL?