I'm pletely new to AWS and have some security issue.
I want to allow my user to upload a profile picture and I want to save it in S3. My code looks like this:
import AWS_S3 from 'aws-sdk/clients/s3';
import config from '../../config';
const myS3Credentials = {
accessKeyId: config('AWSS3AccessKeyID'),
secretAcccessKey: config('AWSS3SecretAccessKey'),
};
console.log('myS3Credentials:', myS3Credentials);
const S3 = new AWS_S3({
credentials: myS3Credentials,
region: config('AWSS3Region'),
});
All of the variables (like AWSS3Region
, and my credentials) are set up in the .env
file. But here, I'm exposing them in the code. How to avoid that? Or should I set up some bucket permissions?
I'm pletely new to AWS and have some security issue.
I want to allow my user to upload a profile picture and I want to save it in S3. My code looks like this:
import AWS_S3 from 'aws-sdk/clients/s3';
import config from '../../config';
const myS3Credentials = {
accessKeyId: config('AWSS3AccessKeyID'),
secretAcccessKey: config('AWSS3SecretAccessKey'),
};
console.log('myS3Credentials:', myS3Credentials);
const S3 = new AWS_S3({
credentials: myS3Credentials,
region: config('AWSS3Region'),
});
All of the variables (like AWSS3Region
, and my credentials) are set up in the .env
file. But here, I'm exposing them in the code. How to avoid that? Or should I set up some bucket permissions?
You can use the aws sdk getSignedUrl method which is exposed on the S3 object. This would allow you to upload to your bucket directly from the client without exposing your access tokens. You can keep your access tokens safe by leaving them in the .env file and keeping that file out of your repo.
Creating signed urls will require creating an endpoint on your server that would return the signed URL. From there you would perform a put request containing the image. I have created a gist with an example. In the gist there is client and server code. https://gist.github./pizza-r0b/35be6dd3e992ef1ebb2159772cb768c0
You should never, ever send/expose AWS access tokens directly in your client code.
Put that code on a server and make calls to your server code, which in turn makes calls to AWS.
On your server, you should never use hardcoded access keys either. Use environmental variables to get the access tokens, as Alejandro stated in his answer below.
Its strongly discouraged to store permanent credentials in your client code to upload files to S3. There are several approaches to handle this securely.
Few references are listed below to get you started with Signed Urls.
Just call on your code process.env.<YOUR_KEY>
.