Signed URLs for private files

Signed URLs #

Signed URLs are used when you want to make a private file (or object), temporarily available. Popular use-cases include digital goods, such as pictures or downloads which are stored in private buckets and customers can download them when a purchase was done.

For the difference private vs. public files, please note: by default all files are private. If you intend to make a file public, please read on here.

Example Code #

The following example uses PHP but would look similar in any other language.

The objective: create a signed-url for the file private-file.pdf.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
require __DIR__ . '/vendor/autoload.php';

use Aws\S3\S3Client;  
use Aws\Exception\AwsException;

$bucket = 'bucket-name.example.org';

$client = new S3Client([
    'credentials' => [
        'access_key_id' => 'your-key-id',
        'secret_access_key' => 'your-secret',
    ],
    'version' => '2006-03-01',
    'endpoint' => 'https://s3.storage.planetary-networks.de',
    'region' => 'us-east-1',
]);

$command = $client->getCommand('GetObject', [
    'Bucket' => $bucket,
    'Key' => 'private-file.pdf'
]);

$request = $client->createPresignedRequest($command, '+20 minutes');
$presignedUrl = (string) $request->getUri();
var_dump($presignedUrl);

The most important part of this example is highlighted above:

  • we created a URL to the file private-file.pdf
  • the URL is valid for the next 20 minutes