S3 upload directly in JavaScript

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 11:53:56

You can use STS to generate short lived temporary credentials for each upload, and pass those to the JS SDK so that you never have to reveal your long term API keys.

Example using AWS PHP SDK (composer package: "aws/aws-sdk-php":"~2.4"), assumes your access_key_id and secret_access_key are available in the ENV.

Sloppy example:

<?php 
include 'vendor/autoload.php';

use Aws\Sts\StsClient;

/** Create Temporary Credentials */
$stsclient = StsClient::factory();
$temp_creds = $stsclient->getSessionToken(900)->get('Credentials'); // 15 minute expiration

?>
<script>
AWS.config.credentials = {
    accessKeyId : '<?php echo $temp_creds['AccessKeyId']; ?>',
    secretAccessKey : '<?php echo $temp_creds['SecretAccessKey']; ?>',
    sessionToken : '<?php echo $temp_creds['SessionToken']; ?>'
};
AWS.config.region = 'your-region';
</script>

This way you never have to reveal your access access_key_id and secret_access_key. The STS generated keys will be invalidated after the set time interval. Be sure to follow best practices, like creating a limited-role IAM user for the long-term stored credentials.

Reference: http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.Sts.StsClient.html#_getSessionToken

You can't hide your credentials in the javascript, as all the code is sent to the client and therefore visible. There are a number of things you could do to work around this though:

  • If the users of your application are trusted and authenticated, you can choose only to serve the script to authenticated users by checking cookies in something like PHP at the top of the file, and setting up your server appropriately to allow this.
  • Alternatively, if the users of your script are untrusted, I would recommend you send requests to your server, rather than S3 directly. Your server can then authenticate and handle the transfer of the file as a proxy, without the key ever being publicly-visible.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!