S3直接在JavaScript中上传
作者:互联网
我正在尝试完成简单操作,并将JavaScript直接上传到Amazon S3.但是,如何隐藏我的访问权限和秘密密钥?我没有在他们的文档或此站点中看到任何答案.
我正在使用他们推荐的方法在HTML中进行设置.我也在使用Backbone和Bower.
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.0.25.min.js"></script>
<script type="text/javascript">
// See the Configuring section to configure credentials in the SDK
AWS.config.credentials = ...;
// Configure your region
AWS.config.region = 'us-west-2';
</script>
<input type="file" id="file-chooser" />
<button id="upload-button">Upload to S3</button>
<div id="results"></div>
<script type="text/javascript">
var bucket = new AWS.S3({params: {Bucket: 'myBucket'}});
var fileChooser = document.getElementById('file-chooser');
var button = document.getElementById('upload-button');
var results = document.getElementById('results');
button.addEventListener('click', function() {
var file = fileChooser.files[0];
if (file) {
results.innerHTML = '';
var params = {Key: file.name, ContentType: file.type, Body: file};
bucket.putObject(params, function (err, data) {
results.innerHTML = err ? 'ERROR!' : 'UPLOADED.';
});
} else {
results.innerHTML = 'Nothing to upload.';
}
}, false);
</script>
解决方法:
您可以使用STS为每次上传生成临时的临时凭证,然后将其传递给JS SDK,这样您就不必透露长期的API密钥.
使用AWS PHP SDK(示例程序包:“ aws / aws-sdk-php”:“〜2.4”)的示例,假设您的access_key_id和secret_access_key在ENV中可用.
马虎的例子:
<?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>
这样,您就不必透露访问权限access_key_id和secret_access_key.在设置的时间间隔后,STS生成的密钥将失效.确保遵循最佳实践,例如为长期存储的凭证创建角色受限的IAM用户.
参考号:http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.Sts.StsClient.html#_getSessionToken
标签:secret-key,javascript,amazon-web-services,amazon-s3 来源: https://codeday.me/bug/20191009/1882469.html