1

My server would communicate with S3. There are two possibilities as far as I understand:

1) Load the file to my server and send it to the user, keeping S3 access only to my server's IP 2) Redirect to S3 while handling authentication on my server

I've understood(I think) how to do #1 from: Does Amazon S3 support HTTP request with basic authentication

But is there any way to accomplish #2? I want to avoid the latency of first loading the file to my server and then sending it to the user.

I'm not sure how to keep the S3 url protected from public access in #2. Someone might go through my authentication, get a download link, but that link will be publicly accessible.

I'm new to S3 in general, so bear with me if I've misunderstood anything.

Edit: I've looked into signed links with expiration times, but they can still be accessed by others. I would also prefer to use my own authentication so I can allow access to a link only while a user is signed in.

Community
  • 1
  • 1
John
  • 3,037
  • 8
  • 36
  • 68

1 Answers1

1

You should try below code, which your server produce an URL which will expire in say 60 seconds, for users to directly download the file from S3 server.

First: Download HMAX.php from here: http://pear.php.net/package/Crypt_HMAC/redirected

<?php
require_once('Crypt/HMAC.php');

echo getS3Redirect("/test.jpg") . "\n";

function getS3Redirect($objectName)
{
  $S3_URL = "http://s3.amazonaws.com";
  $keyId = "your key";
  $secretKey = "your secret";
  $expires = time() + 60;
  $bucketName = "/your bucket";

  $stringToSign = "GET\n\n\n$expires\n$bucketName$objectName";
  $hasher =&amp; new Crypt_HMAC($secretKey, "sha1");
  $sig = urlencode(hex2b64($hasher-&gt;hash($stringToSign)));

  return "$S3_URL$bucketName$objectName?AWSAccessKeyId=$keyId&amp;Expires=$expires&amp;Signature=$sig";
}

function hex2b64($str)
{
    $raw = ";
    for ($i=0; $i &lt; strlen($str); $i+=2)
    {
        $raw .= chr(hexdec(substr($str, $i, 2)));
    }
    return base64_encode($raw);
}

?>

Take a try.

stonyau
  • 2,132
  • 1
  • 20
  • 18