简体   繁体   中英

AWS S3 JavaScript browser upload without access key

I want to upload a file to S3, preferably not through a backend server, but only through browser.

In AWS example, to create an S3 client, I need to provide secret key and secret id:

const S3 = new AWS.S3({
    accessKeyId: <ACCESS_KEY_ID>,
    secretAccessKey: <ACCESS_KEY_SECRET>,
    region: <AWS_REGION>
});

But I don't want to expose my access keys. The website is hosted in CloudFront, is it possible to setup permission between the CloudFront and S3 bucket so that I don't need to provide credentials in JavaScript?

For security reasons you should generally have some way to audit the source of an object upload to S3 (it could afterall be anything if you're allowing public access).

Rather than allowing completely public access it might be better to setup AWS Cognito and use it on your frontend.

You'd have the choice for one of the below scenarios:

  • User signs in via a cognito user
  • The anonymous user is used.

Both of these options will generate temporary credentials that can be used by your frontend. This will prevent a user making a note of them and keeping them forever, ensure you lockdown the permissions to be a putObject only for that specific S3 bucket.

An alternative approach is to use API Gateway and Lambda to generate a presigned URL that can support uploads. For more information on this approach take a look at this article .

To enhance your security it is probably worth adding an S3 event to trigger a Lambda that will validate the object after it has been uploaded.

You need some kind of backend in order to hide your credentials effectively. Since you're already in the AWS universe, you could use an AWS Lambda function that returns a so-called pre-signed upload url to your frontend which you can use to upload your binaries.

More info: AWS S3 Presigned URLs

You need to use S3 presigned URLs. Your backend generates a special URL that contains a signature and send it to the browser. Then the browser can use that URL to send a POST request (or a PUT request, but that is a signed PUT URL) to upload the file directly to the S3 bucket. No access keys are exposed to the client.

You still need to add access keys to your backend, which can be through roles if it is inside AWS. But these keys don't reach the browser, only the signature.

I've written about this topic extensively and also made code examples you can check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM