Download Pre-signed Object
If you want to allow others to receive the object without providing your credential keys, you can use the pre-signed download method.
Components
- Bucket Name
- Object Name
- Link Expiration Time (Optional)
Object Name (Key)
Object name we want to download.
- .NET
- PHP
- Python
- Javascript
- GO
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache - 2.0
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Threading.Tasks;
using System.Reflection;
namespace DownloadPresignedObject
{
class DownloadPresignedObject
{
private static IAmazonS3 _s3Client;
private const string BUCKET_NAME = "<OBJECT_NAME>";
private const string OBJECT_NAME = "<BUCKET_NAME>";
static void Main()
{
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
_s3Client = new AmazonS3Client(awsCredentials, config);
GeneratePreSignedUrl();
}
private static void GeneratePreSignedUrl()
{
try
{
// Create the request
var getPreSignedUrlRequest = new GetPreSignedUrlRequest
{
BucketName = BUCKET_NAME,
Key = OBJECT_NAME,
Expires = DateTime.Now.AddHours(1.0),
Verb = HttpVerb.GET
};
// Submit the request
string url = _s3Client.GetPreSignedURL(getPreSignedUrlRequest);
Console.WriteLine($"URL: {url}");
}
catch (AmazonS3Exception amazonS3Exception)
{
Console.WriteLine("An AmazonS3Exception was thrown. Exception: " + amazonS3Exception.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.ToString());
}
}
}
}
<?php
require('client.php');
$cmd = $client->getCommand('GetObject', [
'Bucket' => $config['sample_bucket'],
'Key' => 'file-uploaded-from-php-sdk.png'
]);
$request = $client->createPresignedRequest($cmd, '+20 minutes');
// Get the actual presigned-url
$presignedUrl = (string)$request->getUri();
echo $presignedUrl;
import boto3
import logging
from botocore.exceptions import ClientError
# Configure logging
logging.basicConfig(level=logging.INFO)
try:
s3_client = boto3.client(
's3',
endpoint_url='endpoint_url',
aws_access_key_id='access_key',
aws_secret_access_key='secret_key'
)
except Exception as exc:
logging.error(exc)
else:
try:
bucket = 'bucket-name'
object_name = 'file.txt'
response = s3_client.generate_presigned_url(
'get_object',
Params={
'Bucket': bucket,
'Key': object_name
},
ExpiresIn=3600
)
except ClientError as e:
logging.error(e)
// Import required AWS SDK clients and commands for Node.js
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
const { S3RequestPresigner } = require('@aws-sdk/s3-request-presigner');
const { createRequest } = require('@aws-sdk/util-create-request');
const { formatUrl } = require('@aws-sdk/util-format-url');
// Create an S3 client service object
const s3 = new S3Client({
region: 'default',
endpoint: 'endpoint_url',
forcePathStyle: false,
credentials: {
accessKeyId: 'access_key',
secretAccessKey: 'secret_key',
},
});
const clientParams = {
Bucket: 'sample_bucket',
Key: 'file.png',
};
const signedRequest = new S3RequestPresigner(s3.config);
const run = async () => {
try {
// Create request
const request = await createRequest(
s3,
// new GetObjectCommand(clientParams)
new GetObjectCommand(clientParams)
);
// Create and format presigned URL
const signedUrl = formatUrl(
await signedRequest.presign(request, {
// Supply expiration in second
expiresIn: 60 * 60 * 24,
})
);
console.log(`download url: ${signedUrl}`);
} catch (err) {
console.log('Error creating presigned URL', err);
}
};
run();
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
// Downloads an item from an S3 Bucket
//
// Usage:
// go run s3_download_presigned.go BUCKET FILE_NAME
func main() {
if len(os.Args) != 3 {
exitErrorf("Bucket name required\nUsage: go run", os.Args[0], "BUCKET", "FILE_NAME")
}
bucket := os.Args[1]
filename := os.Args[2]
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials("<ACCESS_KEY>", "<SECRET_KEY>", ""),
})
svc := s3.New(sess, &aws.Config{
Region: aws.String("default"),
Endpoint: aws.String("<ENDPOINT_URL>"),
})
req, _ := svc.GetObjectRequest(&s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(filename),
})
urlStr, err := req.Presign(15 * time.Minute)
if err != nil {
log.Println("Failed to sign request", err)
}
log.Println("The URL is", urlStr)
}
// snippet-start:[s3.go.set_cors.exit]
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
The following command can be used to execute the aforementioned code, presuming the code file is called s3_get_bucket_cors.go:
go run s3_download_presigned.go BUCKET FILE_NAME