Skip to content

Instantly share code, notes, and snippets.

@berkedel
Last active May 29, 2020 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berkedel/73ec2ef46dacb7d5557108539a16fc14 to your computer and use it in GitHub Desktop.
Save berkedel/73ec2ef46dacb7d5557108539a16fc14 to your computer and use it in GitHub Desktop.
Create AWS S3 Presigned Download Url

Create AWS S3 Presigned Download Url

References:

public class AwsS3Utility {
    static String BUCKET_NAME = 'YOUR_BUCKET_NAME';
    static String ACCESS_KEY = 'YOUR_ACCESS_KEY';
    static String SECRET_KEY = 'YOUR_SECRET_KEY';

    public static String getSignedDownloadUrl(String bucketKey, Integer expiresInSec) {
        Datetime now = DateTime.now();
        Datetime expiresAt = now.AddSeconds(expiresInSec); // Lifespan of the link
        Long expires = expiresAt.getTime() / 1000;

        String stringToSign = 'GET\n\n\n' + expires + '\n/' + BUCKET_NAME + '/' + bucketKey;
        System.debug('redirectToS3Key stringToSign: ' + stringToSign);

        String signingKey = EncodingUtil.base64Encode(Blob.valueOf(SECRET_KEY));
        Blob mac = Crypto.generateMac('HMacSHA1', Blob.valueof(stringToSign), Blob.valueof(SECRET_KEY));
        String signed= EncodingUtil.base64Encode(mac);
        String codeSigned = EncodingUtil.urlEncode(signed,'UTF-8');
        String url = 'https://' + BUCKET_NAME + '.s3.amazonaws.com/' + bucketKey + '?AWSAccessKeyId=' + ACCESS_KEY + '&Expires=' + expires + '&Signature=' + codeSigned;
        return url;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment